我创建了一个节点js程序:data.js:位置是控制器data.js
var myPythonScriptPath = 'script.py';
const {PythonShell} = require("python-shell");
var pyshell = new PythonShell(myPythonScriptPath);
var moduel= pyshell.on('message', function (message) {
console.log(message);
});
pyshell.end(function (err) {
if (err){
throw err;
};
console.log('finished');
});
我创建了一个表达框架:APP.JS:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
pyshell.stdout.on('data', function(data) {
console.log(data.toString());
res.write(data);
res.end('end');
});
})
app.listen(4000, () => console.log('Application listening on port 4000!'));
我想打开APP.JS文件中的data.js文件,以便它可以路由到存储在controllers文件夹中的data.js文件,并在服务器上显示data.js的数据。
答案 0 :(得分:0)
使用module.exports导出文件中的任何功能。
//server.js
var ctrl = require('./controllers/data.js');
app.get('/', ctrl.getData);
//controllers/data.js
var myPythonScriptPath = 'script.py';
const {PythonShell} = require("python-shell");
var pyshell = new PythonShell(myPythonScriptPath);
function getData(req, res){
// do your pyShell activities here.
// sends a message to the Python script via stdin
pyshell.send('hello');
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
res.send(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err,code,signal) {
if (err) throw err;
console.log('The exit code was: ' + code);
console.log('The exit signal was: ' + signal);
console.log('finished');
console.log('finished');
});
}
module.exports = {
getData: getData
}