Node.js 在express中加载js文件
我已经创建了一个节点js程序:data.js:location is controllers data.jsNode.js 在express中加载js文件,node.js,express,Node.js,Express,我已经创建了一个节点js程序:data.js:location is controllers data.js var myPythonScriptPath = 'script.py'; const {PythonShell} = require("python-shell"); var pyshell = new PythonShell(myPythonScriptPath); var moduel= pyshell.on('message', function (message) { co
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');
});
我创建了一个express框架: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的数据。使用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
}
但它没有使用“module.export”加载文件。如果不使用module.exports,您也可以从server.js访问getData函数?不,很抱歉,它不起作用…我犯了一个错误,在同一个目录中运行了旧文件…请您编写完整的代码,这样我就可以看到我包括了哪些错误,因为我无法实现它。这真是帮了大忙,先生。