Nodejs:如何在使用child_process的spawn时使用nvm更改节点版本

时间:2021-05-30 07:27:07

I used spawn to run a script, but the script needs node8.x while my default version is 6.

我使用spawn来运行脚本,但脚本需要node8.x而我的默认版本是6。

so, how to change node version with nvm while using child_process's spawn

那么,如何在使用child_process的spawn时使用nvm更改节点版本

let linkstart = ()=>{
    let cp = spawn('node', ['dist/app.js']);

    cp.stderr.on('data', (data)=>{
        console.error('stderr: ', data.toString('utf8'));
    })

    cp.stdout.on('data', (data)=>{
        console.info('stdout: ', data.toString('utf8'));
    })

    return cp;
}

2 个解决方案

#1


0  

You can modify your code, to call a script function, which in-turn switches the shell's node version (using nvm), then calls the script.

您可以修改代码,调用脚本函数,然后依次切换shell的节点版本(使用nvm),然后调用脚本。

#!/bin/sh

nvm use v8.7.0
node dist/app.js

I tried to do something like

我试着做点什么

let cp = spawn('nvm', ['use', 'v8.7.0', ';', 'node', 'dist/app.js']);

But it gives the following error

但它给出了以下错误

Error: spawn nvm ENOENT

On, digging further on it, seems we cannot call nvm directly from any node script, reasoning for it is given here @Github. I'll try looking further down if any other possible solution exists :)

在,进一步挖掘它,似乎我们不能直接从任何节点脚本调用nvm,这里给出了@Github的推理。如果存在任何其他可能的解决方案,我会尝试进一步查看:)

Hope this helps!

希望这可以帮助!

#2


0  

if you're running .js file. you need to use process.fork

如果您正在运行.js文件。你需要使用process.fork

let setup = {
  execPath : '/home/User/.nvm/v8.7.0/bin/node' ,   // path to binary
  cwd: Path to dist/
  stdio : [0, 1, 2, 'ipc']       // [process.stdin, process.stdout, process.stderr, ipc]
}

let fork = require('child_process').fork;
let child = fork('app.js', setup);

#1


0  

You can modify your code, to call a script function, which in-turn switches the shell's node version (using nvm), then calls the script.

您可以修改代码,调用脚本函数,然后依次切换shell的节点版本(使用nvm),然后调用脚本。

#!/bin/sh

nvm use v8.7.0
node dist/app.js

I tried to do something like

我试着做点什么

let cp = spawn('nvm', ['use', 'v8.7.0', ';', 'node', 'dist/app.js']);

But it gives the following error

但它给出了以下错误

Error: spawn nvm ENOENT

On, digging further on it, seems we cannot call nvm directly from any node script, reasoning for it is given here @Github. I'll try looking further down if any other possible solution exists :)

在,进一步挖掘它,似乎我们不能直接从任何节点脚本调用nvm,这里给出了@Github的推理。如果存在任何其他可能的解决方案,我会尝试进一步查看:)

Hope this helps!

希望这可以帮助!

#2


0  

if you're running .js file. you need to use process.fork

如果您正在运行.js文件。你需要使用process.fork

let setup = {
  execPath : '/home/User/.nvm/v8.7.0/bin/node' ,   // path to binary
  cwd: Path to dist/
  stdio : [0, 1, 2, 'ipc']       // [process.stdin, process.stdout, process.stderr, ipc]
}

let fork = require('child_process').fork;
let child = fork('app.js', setup);