I have a C++
program and a Python
script that I want to incorporate into my node.js
web app.
我有一个c++程序和一个Python脚本,我想把它们合并到我的节点中。js web应用程序。
I want to use them to parse the files that are uploaded to my site; it may take a few seconds to process, so I would avoid to block the app as well.
我想用它们来解析上传到我网站的文件;可能需要几秒钟的时间来处理,所以我也会避免屏蔽这个应用。
How can I just accept the file then just run the C++
program and script in a sub-process from a node.js
controller?
如何接受文件,然后在节点的子进程中运行c++程序和脚本。js控制器吗?
1 个解决方案
#1
35
see child_process. here is an example using spawn
, which allows you to write to stdin and read from stderr/stdout as data is output. If you have no need to write to stdin and you can handle all output when the process completes, child_process.exec
offers a slightly shorter syntax to execute a command.
看到child_process。这里有一个使用spawn的示例,它允许您将数据写入stdin并在输出时从stderr/stdout中读取。如果您不需要写到stdin,并且可以在进程完成时处理所有输出,那么child_process。exec提供了更短的语法来执行命令。
// with express 3.x
var express = require('express');
var app = express();
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);
app.post('/upload', function(req, res){
if(req.files.myUpload){
var python = require('child_process').spawn(
'python',
// second argument is array of parameters, e.g.:
["/home/me/pythonScript.py"
, req.files.myUpload.path
, req.files.myUpload.type]
);
var output = "";
python.stdout.on('data', function(data){ output += data });
python.on('close', function(code){
if (code !== 0) {
return res.send(500, code);
}
return res.send(200, output);
});
} else { res.send(500, 'No file found') }
});
require('http').createServer(app).listen(3000, function(){
console.log('Listening on 3000');
});
#1
35
see child_process. here is an example using spawn
, which allows you to write to stdin and read from stderr/stdout as data is output. If you have no need to write to stdin and you can handle all output when the process completes, child_process.exec
offers a slightly shorter syntax to execute a command.
看到child_process。这里有一个使用spawn的示例,它允许您将数据写入stdin并在输出时从stderr/stdout中读取。如果您不需要写到stdin,并且可以在进程完成时处理所有输出,那么child_process。exec提供了更短的语法来执行命令。
// with express 3.x
var express = require('express');
var app = express();
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);
app.post('/upload', function(req, res){
if(req.files.myUpload){
var python = require('child_process').spawn(
'python',
// second argument is array of parameters, e.g.:
["/home/me/pythonScript.py"
, req.files.myUpload.path
, req.files.myUpload.type]
);
var output = "";
python.stdout.on('data', function(data){ output += data });
python.on('close', function(code){
if (code !== 0) {
return res.send(500, code);
}
return res.send(200, output);
});
} else { res.send(500, 'No file found') }
});
require('http').createServer(app).listen(3000, function(){
console.log('Listening on 3000');
});