Javascript 合并两个代码
我在Node js中有2个文件。我想合并这2个文件,但我遇到了问题。。 此文件从python文件调用函数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
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
,必须包装在函数中,而您的方法将在加载脚本本身时立即开始承诺runPy
中,必须在pyprogr
关闭事件时解决/拒绝spawn
/exec
时,您必须记住,您不是执行脚本的用户,而是节点
用户,因此可能会出现不同的结果打印/ECHO
到shell,不返回!最好的方法是打印一些json字符串,并在外壳关闭后在javascript中解析它,这样您就可以访问对象而不是字符串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
,必须包装在函数中,而您的方法将在加载脚本本身时立即开始承诺runPy
中,必须在pyprogr
关闭事件时解决/拒绝spawn
/exec
时,您必须记住,您不是执行脚本的用户,而是节点
用户,因此可能会出现不同的结果打印/ECHO
到shell,不返回!最好的方法是打印一些json字符串,并在外壳关闭后在javascript中解析它,这样您就可以访问对象而不是字符串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代码。