Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 合并两个代码_Javascript_Python_Html_Node.js_Nodejs Server - Fatal编程技术网

Javascript 合并两个代码

Javascript 合并两个代码,javascript,python,html,node.js,nodejs-server,Javascript,Python,Html,Node.js,Nodejs Server,我在Node js中有2个文件。我想合并这2个文件,但我遇到了问题。。 此文件从python文件调用函数 const app = express() let runPy = new Promise(function(success, nosuccess) { const { spawn } = require('child_process'); const pyprog = spawn('python', ['./ml.py']); pyprog.stdout.on

我在Node js中有2个文件。我想合并这2个文件,但我遇到了问题。。 此文件从python文件调用函数

const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./ml.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(testMLFunction) {
        console.log(testMLFunction.toString());
        res.end(testMLFunction);
    });
})
app.listen(4000, () => console.log('Application listening on port 4000!'))
python文件ml.py

def testMLFunction():
return "hello from Python"
打印(testMLFunction())

下面的文件工作在按钮上单击并使用post方法

var fs = require('fs');

var server = http.createServer(function (req, res) {

    if (req.method === "GET") {
        res.writeHead(200, { "Content-Type": "text/html" });
        fs.createReadStream("./form.html", "UTF-8").pipe(res);
    } else if (req.method === "POST") {

        var result = "";
        req.on("data", function (chunk) {
            console.log(chunk.toString());

            result = chunk;
            //body=body.toUpperCase;
        });

        req.on("end", function(){
            res.writeHead(200, { "Content-Type": "text/html" });
            res.end(result);
        });
    }

}).listen(3000);

我怎样才能做到这一点。

这里有几件事不对。我将尽可能清楚地解释

  • 您忘记添加代码
    var express=require('express')
  • 您做出的承诺,
    runPy
    ,必须包装在函数中,而您的方法将在加载脚本本身时立即开始承诺
  • 在第一次传入输出时,您正在解析/拒绝,您不应该这样做,因为您无法知道shell中到底发生了什么。您需要存储这些输出行,这是了解脚本告诉您什么的唯一方法
  • runPy
    中,必须在
    pyprogr
    关闭事件时解决/拒绝
  • 您无法直接访问另一个脚本的方法,无论该类文件是py、sh、bat、js。但是,您可以通过向shell传递参数来访问它的内部函数,当然,该脚本必须具有处理这些参数所需的逻辑
  • 使用
    spawn
    /
    exec
    时,您必须记住,您不是执行脚本的用户,而是
    节点
    用户,因此可能会出现不同的结果
  • 最重要的是,您的目标脚本必须
    打印/ECHO
    到shell,不返回!最好的方法是打印一些json字符串,并在外壳关闭后在javascript中解析它,这样您就可以访问对象而不是字符串
  • 下面您将看到一个演示对于您的用例,我更改了python文件以便它可以打印一些东西

    ml.py

    print('I\'m the output from ml.py')
    
    index.js

    const express = require('express');
    const app = express()
    
    let runPy = function () { // the promise is now wrapped in a function so it won't trigger on script load
        return new Promise(function (success, nosuccess) {
    
            const {spawn} = require('child_process');
            const pyprog = spawn('python', ['./ml.py'], {shell: true}); // add shell:true so node will spawn it with your system shell.
    
            let storeLines = []; // store the printed rows from the script
            let storeErrors = []; // store errors occurred
            pyprog.stdout.on('data', function (data) {
                storeLines.push(data);
            });
    
            pyprog.stderr.on('data', (data) => {
                storeErrors.push(data);
            });
            pyprog.on('close', () => {
                // if we have errors will reject the promise and we'll catch it later
                if (storeErrors.length) {
                    nosuccess(new Error(Buffer.concat(storeErrors).toString()));
                } else {
                    success(storeLines);
                }
            })
        })
    };
    
    let path = require('path');
    app.use(express.json());
    app.use(express.urlencoded({ extended: true })); // you need to set this so you can catch POST requests
    app.all('/', (req, res) => { // i've change this from .get to .all so you can catch both get and post requests here
    
        console.log('post params', req.body);
    
        if(req.body.hasOwnProperty('btn-send')){
    
            runPy()
                .then(function (pyOutputBuffer) {
    
                    let message = 'You sent this params:\n' +JSON.stringify(req.body, null,2) + '\n';
                    message += Buffer.concat(pyOutputBuffer).toString();
    
                    res.end(message);
    
                })
                .catch(console.log)
        }else{
            res.sendFile(path.join(__dirname,'form.html')); // you need an absolute path to 'file.html'
        }
    
    });
    app.listen(4000, () => console.log('Application listening on port 4000!'));
    
    form.html

    <div>hello there</div>
    <form action="/" method="post">
        <input type="text" value="" name="some-text"/>
        <button type="submit" value="1" name="btn-send" >Press me!</button>
    </form>
    
    你好 按我!
    这里有几个地方出了问题。我将尽可能清楚地解释

  • 您忘记添加代码
    var express=require('express')
  • 您做出的承诺,
    runPy
    ,必须包装在函数中,而您的方法将在加载脚本本身时立即开始承诺
  • 在第一次传入输出时,您正在解析/拒绝,您不应该这样做,因为您无法知道shell中到底发生了什么。您需要存储这些输出行,这是了解脚本告诉您什么的唯一方法
  • runPy
    中,必须在
    pyprogr
    关闭事件时解决/拒绝
  • 您无法直接访问另一个脚本的方法,无论该类文件是py、sh、bat、js。但是,您可以通过向shell传递参数来访问它的内部函数,当然,该脚本必须具有处理这些参数所需的逻辑
  • 使用
    spawn
    /
    exec
    时,您必须记住,您不是执行脚本的用户,而是
    节点
    用户,因此可能会出现不同的结果
  • 最重要的是,您的目标脚本必须
    打印/ECHO
    到shell,不返回!最好的方法是打印一些json字符串,并在外壳关闭后在javascript中解析它,这样您就可以访问对象而不是字符串
  • 下面您将看到一个演示对于您的用例,我更改了python文件以便它可以打印一些东西

    ml.py

    print('I\'m the output from ml.py')
    
    index.js

    const express = require('express');
    const app = express()
    
    let runPy = function () { // the promise is now wrapped in a function so it won't trigger on script load
        return new Promise(function (success, nosuccess) {
    
            const {spawn} = require('child_process');
            const pyprog = spawn('python', ['./ml.py'], {shell: true}); // add shell:true so node will spawn it with your system shell.
    
            let storeLines = []; // store the printed rows from the script
            let storeErrors = []; // store errors occurred
            pyprog.stdout.on('data', function (data) {
                storeLines.push(data);
            });
    
            pyprog.stderr.on('data', (data) => {
                storeErrors.push(data);
            });
            pyprog.on('close', () => {
                // if we have errors will reject the promise and we'll catch it later
                if (storeErrors.length) {
                    nosuccess(new Error(Buffer.concat(storeErrors).toString()));
                } else {
                    success(storeLines);
                }
            })
        })
    };
    
    let path = require('path');
    app.use(express.json());
    app.use(express.urlencoded({ extended: true })); // you need to set this so you can catch POST requests
    app.all('/', (req, res) => { // i've change this from .get to .all so you can catch both get and post requests here
    
        console.log('post params', req.body);
    
        if(req.body.hasOwnProperty('btn-send')){
    
            runPy()
                .then(function (pyOutputBuffer) {
    
                    let message = 'You sent this params:\n' +JSON.stringify(req.body, null,2) + '\n';
                    message += Buffer.concat(pyOutputBuffer).toString();
    
                    res.end(message);
    
                })
                .catch(console.log)
        }else{
            res.sendFile(path.join(__dirname,'form.html')); // you need an absolute path to 'file.html'
        }
    
    });
    app.listen(4000, () => console.log('Application listening on port 4000!'));
    
    form.html

    <div>hello there</div>
    <form action="/" method="post">
        <input type="text" value="" name="some-text"/>
        <button type="submit" value="1" name="btn-send" >Press me!</button>
    </form>
    
    你好 按我!
    非常感谢你美丽的解释…我明白我错在哪里了..但还有一个问题..我们可以通过HTML中的按钮单击来完成所有这些..有没有任何方法..或其他方法/过程..你需要捕获post请求。我已经更新了我的答案,使用了
    form.html
    ,其中包含按钮(只需从下面的
    let path
    复制即可)。这只是一个例子,我建议您检查一下模板引擎,例如
    ejs
    ,它在express中非常流行,它将帮助您将值直接绑定到html代码。非常感谢您美丽的解释…我理解我错在哪里了…但还有一个问题..我们可以通过从html单击按钮来完成所有这些..有什么方法..或其他方法吗方法/过程..您需要捕获post请求。我已经更新了我的答案,使用了
    form.html
    ,其中包含按钮(只需从下面的
    let path
    复制即可)。这只是一个例子,我建议您检查一下模板引擎,例如express中非常流行的
    ejs
    ,它将帮助您将值直接绑定到html代码。