繁体   English   中英

在 express js 服务器中使用节点应用程序

[英]Using node app inside an express js server

我有一个具有以下目录结构的 Express js 服务器端点:

  • 应用程序.js
  • 节点模块
  • 封装锁.json
  • package.json
  • mrz检测

mrz-detection 目录包含一个节点应用程序,我通常会从命令行调用它,例如node run/getMrz.js --file passport.jpg

我的 app.js 看起来像这样

const { getMrz } = require('./mrz-detection');
const fs = require('fs');
const app = express()
const port = 3000
const bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '10mb', extended: true}));
var passportsArr = [];


app.post('/', function(req, res) {
    var passport = req.body;
    let buff = new Buffer(passport.data, 'base64');
    fs.writeFileSync('passport.png', buff);
    // send passport photo to mrz-detection app here
})

app.listen(port, () => console.log(`Mrz detection app listening at http://localhost:${port}`))

我需要从 app.js 中的帖子路由调用 mrz-detection 应用

我该怎么做?

我可以想到两种方法来做到这一点:

  1. 按照评论员的解释调用其他程序命令行样式
  2. 重构您的代码,以便您可以简单地从其他文件中导入 function 并使用它。 我会更推荐这个,因为它允许潜在地传递复杂的参数,而不必在命令行中对它们进行序列化和反序列化。

您可以将应用程序作为子进程启动:

https://nodejs.org/api/child_process.html

产生子进程有几个不同的“child_process”函数

execFile 派生叉

使用 fork,在父子之间发送消息会自动工作

const fork = require('child_process').fork;
const child = fork('/path/to/app.js', ['optional', 'arguments']);

// message from child
child.on('message', (msg) => {
    console.log('message from child ' + msg);
}

// send message to child
child.send({hi:'hi from parent'});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM