据我了解。当有请求到达您的服务器时,您希望从 Python 模块获取数据,而不仅仅是提供纯文本源文件。
正如您所见,res.sendFile(__dirname + '/Controllers'); 行将发送文件本身,它不会执行它并提供您发送到控制台的任何文件。
要实现我之前所说的,您需要导入您的 JS 文件(在 commonjs 中,这称为需要模块),然后调用函数从那里获取数据(如果您想将服务器逻辑与 python shell 逻辑分开)。
在 python-shell.js 中,您需要获取作为app.get('/', function(req, res) {}) 回调的一部分提供的 res 对象。所以我会用以下方式重组代码:
python-shell.js
// Note that script.py refers to /script.py, not /Controllers/script.py
// As code bellow won't be called from within python-shell.js. More on that later
const myPythonScriptPath = 'script.py';
// Use python shell
const { PythonShell } = require("python-shell");
// From this file (module) we are exporting function
// that takes req and res parameters provided by app.get callback
// Note that this file is not executed by itself, it only exposes
// a single function to whom is gonna import it
module.exports = function (req, res) {
const pyshell = new PythonShell(myPythonScriptPath);
// Create buffer to hold all the data produced
// by the python module in it's lifecycle
let buffer = "";
module = pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
// On every message event add that chunk to buffer
// We add \n to the end of every message to make it appear from the new line (as in python shell)
buffer += message + '\n';
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err) {
// If error encoutered just send it to whom requested it
// instead of crashing whole application
res.statusCode = 500;
res.end(err.message);
}
// res.end sends python module outputs as a response to a HTTP request
res.end(buffer);
console.log('finished');
});
}
在 server.js 内部:
const express = require("express")
const path = require('path');
// We are importing our function from Controllers/python-shell.js file
// and storing it as variable called pythonShellHandler
const pythonShellHandler = require("./Controllers/python-shell")
const app = express();
// express.static will serve source files from the directory
app.use(express.static(path.join(__dirname, 'Controllers')));
// Here we are passing our imported function as a callback
// to when we are recieving HTTP request to the root (http://localhost:3000/)
app.get('/', pythonShellHandler);
app.listen(3000, function () {
console.log('Listening');
})
如您所见。我重组了您的代码,以便 python-shell.js 将一个函数导出到其他 .js 文件,该函数采用 Express 的 req 和 res 参数。我从 server.js 中导入了这个函数。
这个 Node.js 模块系统一开始可能有点难以理解。如果您仍然感到困惑,我建议您阅读node modules
注意:如果您的 python 脚本需要很长时间才能完成,或者根本没有完成。浏览器只会让您的请求超时。