【问题标题】:Open file in one directory to another in node js在节点js中将一个目录中的文件打开到另一个目录
【发布时间】:2020-04-30 03:54:34
【问题描述】:

我创建了位于 Controllers 目录中的程序 python-shell.js。这个程序给出了一些数据。

python-shell.js:代码:

 var myPythonScriptPath = 'script.py';

// Use python shell
    const {PythonShell} = require("python-shell");
    var pyshell = new PythonShell(myPythonScriptPath);

    module = pyshell.on('message', function (message) {
    // received a message sent from the Python script (a simple "print" statement)
        console.log(message);
    });

    // end the input stream and allow the process to exit
    pyshell.end(function (err) {
    if (err){
        throw err;
    };

    console.log('finished');
    });

我在控制器目录之外创建了另一个 server.js 文件。就是运行python-shell.js文件。

server.js:代码

var app = express();
var path = require('path');

app.use(express.static(path.join(__dirname, 'Controllers')));

app.get('/', function(req,res){
    res.sendFile(__dirname + '/Controllers');
});
app.listen(3000,function() {
console.log('Listening');
})

但是这个 server.js 代码提供了我在“python-shell.js”文件中编写的代码。但我希望 server.js 提供“python-shell.js”在独立运行时提供的数据,而不是提供代码。

【问题讨论】:

    标签: python node.js


    【解决方案1】:

    据我了解。当有请求到达您的服务器时,您希望从 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 脚本需要很长时间才能完成,或者根本没有完成。浏览器只会让您的请求超时。

    【讨论】:

    • 因此,当我尝试运行 python_shell.py 时,它没有给我任何输出,但是当我尝试使用以前的代码时,它给了我输出。在 server.js 部分,当我尝试运行时,它给了我 :: (null): can't open file 'script.py': [Errno 2] No such file or directory。你能告诉我如何解决吗?这真的很有帮助。
    • 是的,通过这些更改 python-shell.js 不执行函数。它现在只将它公开给其他 js 文件。关于错误。正如我在 cmets 中所说,代码变量 myPythonScriptPath 现在不是指 /Controlles/script.py,而是指 /script.py。因为我们没有执行python-shell.js,所以我们节点进程的起始位置是server.js,它位于Controllers文件夹之外。
    • @Ajax,我想您的 script.py 文件位于 Controllers 文件夹中。尝试将其移到外面,或将myPythonScriptPath 的值更改为"Controllers/script.py"
    • 我将 myPythonScriptPath 的路径提供给 /controllers/script.py 所以它显示了输出.....因为我尝试了 const myPythonScriptPath = './controllers/script.py' 但仍然给了我同样的错误:无法打开文件'wikipedia.py':[Errno 2] 没有这样的文件或目录
    • 如果你想以你提供的形式从server.js访问python-shell.js,恐怕做不到。您需要重组代码以使用节点的模块系统(我已经完成了)。如果使用节点执行,这样做会失去文件执行任何有意义代码的能力,除非您使用this trick。关于文件未找到错误。我唯一能注意到的可能是检查您是否输入了正确的路径并且文件存在于指定的路径中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2010-11-11
    • 2017-07-20
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多