首页 > 解决方案 > 需要从另一个 NodeJs 应用程序运行 NodeJs 应用程序

问题描述

我在以下目录中运行了一个 NodeJs 应用程序

第一个应用程序的路径“/users/user1/projects/sampleProject”3000端口上运行。

第二个应用程序的路径“/users/user1/demoProjects/demo1”将在第一个应用程序触发路由器功能时在5000端口运行。

第二个 NodeJs 应用程序尚未启动(它将在端口 5000 上运行)。它需要在第一个运行在 3000 端口(即http://localhost:3000/server/startServer)上的 NodeJs 应用程序中的路由器功能上独立运行。我是 NodeJs 子进程的新手,如果我错了,请纠正我。并建议我一个正确的方法。谢谢

使用 node.js 启动另一个节点应用程序?

我已经尝试过如下

// 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
        });
    }    
});

上面的代码执行命令并触发第二个应用程序在后台运行,但它不返回任何内容。错误或成功结果。

标签: node.jschild-process

解决方案


您需要使用stoutstderror检查其他服务器日志。你的代码也不正确。如果你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
        });
    }
});

推荐阅读