[英]How do I start js app from another js app?
I have to execute an ansync function before execute an express server, because I'm going to get a aparameter to pass it to the API. 在执行Express Server之前,我必须执行ansync函数,因为我将获得一个参数以将其传递给API。 So I guess I can call the async funcion and on the promise I will get, call my express server (until now I have exectued it with "node my_server.js") How can I do that? 因此,我想我可以打电话给异步函数,并保证可以打电话给我的快递服务器(直到现在我已经用“ node my_server.js”执行它了)我该怎么办? How can I call my_server.js on my new js ? 如何在新js上调用my_server.js?
You can fork
a new process using the child_process
module in node. 您可以使用node中的child_process
模块fork
一个新进程。
const { fork } = require('child_process')
const path = require('path')
const newProcess = fork(path.join(__dirname, 'path/to/jsfile'), [...otherArgs])
Usually the server does not get created while merely running node server.js
. 通常,仅在运行node server.js
时不会创建服务器。 It will just execute javascript contained in server.js
. 它将只执行server.js
包含的javascript。 The server will be created when your code reaches express()
if you are creating server via express or createServer
from plain nodejs. 如果您通过express或createServer
从纯nodejs创建服务器,则代码到达express()
时将创建服务器。
That means you can probably do 这意味着您可能可以做
var param = await someSync();
// Set the param in global context and then create your server
var app = express();
// or
var app = createHttpServer()
So now before your app starts you will have that param and you can use it in your api 因此,现在在您的应用开始之前,您将拥有该参数,并且可以在api中使用它
If you are using promise instead of async, just create your server in then
part of your promise, this will also make sure that your app will have that param before your server starts 如果您使用的承诺,而不是异步,只需在创建服务器then
你的承诺的一部分,这也将确保你的服务器开始之前您的应用程序将有PARAM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.