node.js - 需要从另一个 NodeJs 应用程序运行 NodeJs 应用程序
问题描述
我在以下目录中运行了一个 NodeJs 应用程序
第一个应用程序的路径“/users/user1/projects/sampleProject”在3000端口上运行。
第二个应用程序的路径“/users/user1/demoProjects/demo1”将在第一个应用程序触发路由器功能时在5000端口运行。
第二个 NodeJs 应用程序尚未启动(它将在端口 5000 上运行)。它需要在第一个运行在 3000 端口(即http://localhost:3000/server/startServer)上的 NodeJs 应用程序中的路由器功能上独立运行。我是 NodeJs 子进程的新手,如果我错了,请纠正我。并建议我一个正确的方法。谢谢
我已经尝试过如下
// First NodeJs application
import { exec } from "child_process";
router.get('/startServer', async (req, res, next) => {
console.log("Initiated request")
let startServerInstance = 'cd "/users/user1/demoProjects/demo1" && npm run dev'; // path for the second NodeJs application
console.log("Server instance path => " + startServerInstance)
try {
// exec from child process, Spawns a shell then executes the command within that shell
let child = exec(startServerInstance, function (err, stdout, stderr) {
if (err) throw err;
else {
console.log("result ")
res.json({
status: 'success'
});
}
});
} catch (error) {
res.json({
status: 'error',
message: error
});
}
});
上面的代码执行命令并触发第二个应用程序在后台运行,但它不返回任何内容。错误或成功结果。
解决方案
您需要使用stout
并stderror
检查其他服务器日志。你的代码也不正确。如果你if
不使用{}
它就不会去else
声明。这就是为什么您在控制台中看不到“结果”文本的原因。
import {
exec
} from "child_process";
router.get('/startServer', async (req, res, next) => {
console.log("Initiated request")
let startServerInstance = 'cd "/users/user1/demoProjects/demo1" && npm run dev'; // path for the second NodeJs application
console.log("Server instance path => " + startServerInstance)
try {
// exec from child process, Spawns a shell then executes the command within that shell
let child = exec(startServerInstance, function(err) {
if (err) throw err;
console.log("Server started");
});
child.stdout.on('data', (data) => {
// this is new server output
console.log(data.toString());
});
child.stderr.on('data', (data) => {
// this is new server error output
console.log(data.toString());
});
res.json({
status: 'success'
});
} catch (error) {
res.json({
status: 'error',
message: error
});
}
});
推荐阅读
- react-native - 有谁知道如何在 React Native 中创建这个组件?
- c++ - 如何在 QtCreator 中使用 qmake 和 MinGW32 链接动态库?
- java - 如何使用 Executor Framework 使用所有 4 个 CPU 内核执行操作?
- sitecore - 如何在 Sitecore SXA 元数据部分设计中使用令牌?
- orm - 区分 knex 客户端和 knex 事务
- meteor - 如何将数据变量从每个传递到流星中的with?
- java - 找不到带有 H2 投掷表的 Spring MVC
- reactjs - 同一个 Azure 存储帐户上的多个 React 站点
- node.js - 在我的代码中读取和写入文件是非阻塞的。为什么?
- python - 试图将 json 转换为 csv,index_col 错误