简体   繁体   English

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

[英]Using node app inside an express js server

I have an Express js server endpoint with the following directory structure:我有一个具有以下目录结构的 Express js 服务器端点:

  • app.js应用程序.js
  • node_modules节点模块
  • package-lock.json封装锁.json
  • package.json package.json
  • mrz-detection mrz检测

The mrz-detection directory, contains a node app which I would normally call from the command line like this node run/getMrz.js --file passport.jpg mrz-detection 目录包含一个节点应用程序,我通常会从命令行调用它,例如node run/getMrz.js --file passport.jpg

My app.js looks like this我的 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}`))

I need to call the mrz-detection app from my post route in the app.js我需要从 app.js 中的帖子路由调用 mrz-detection 应用

How would I do that?我该怎么做?

There are two ways I can think of to do this:我可以想到两种方法来做到这一点:

  1. Call the other program command-line-style as explained by a commentor按照评论员的解释调用其他程序命令行样式
  2. Refactor your code so that you can simply import a function from your other file and use it.重构您的代码,以便您可以简单地从其他文件中导入 function 并使用它。 I would recommend this more because it allows for complex parameters to potentially be passed without having to serialize and deserialize them in the command line.我会更推荐这个,因为它允许潜在地传递复杂的参数,而不必在命令行中对它们进行序列化和反序列化。

You could you start the app as a child process:您可以将应用程序作为子进程启动:

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

There are a few different 'child_process' functions for spawning child processes产生子进程有几个不同的“child_process”函数

execFile spawn fork execFile 派生叉

With fork, sending messages between parent and child works automatically使用 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