How to execute locally installed Node.js application by child_process.spawn()?

泪湿孤枕 提交于 2019-12-07 09:33:42

As discussed in the chat, the error you are getting is usually caused by the fact that the executable you are trying to run is not available

Now there are multiple reasons the executable may not be available

  1. The executable is not there at all anywhere on the system
  2. The executable is there but not in the folders defined by system's PATH variable
  3. The executable is there in the current directory but the directory context in which the process is being run is different

To fix #1 and #2 you just install the executable globally in system PATH

For fixing #3 you can do two things. Add the path for the current directory ({ cwd: __dirname}) and also a relative path to executable

const childProcess: ChildProcess__type = ChildProcess.spawn( 
Path.resolve(__dirname, 'node_modules/.bin/electron'), 
[ Path.resolve(__dirname, 'ProjectInitializer__ElectronMain.js') ], 
{ cwd: __dirname} 
); 

or

const childProcess: ChildProcess__type = ChildProcess.spawn( 
'./node_modules/.bin/electron'), 
[ Path.resolve(__dirname, 'ProjectInitializer__ElectronMain.js') ], 
{ cwd: __dirname} 
); 

or

const childProcess: ChildProcess__type = ChildProcess.spawn( 
'node_modules/.bin/electron', 
[ './ProjectInitializer__ElectronMain.js' ], 
{ cwd: __dirname} 
); 

In case you decide to override the PATH environment variable you can do it passing the env parameters with more values

const childProcess: ChildProcess__type = ChildProcess.spawn( 
'node_modules/.bin/electron', 
[ './ProjectInitializer__ElectronMain.js' ], 
{ cwd: __dirname, env: {....}} 
); 

You can use the existing environment variables from process.env and then update the same, and pass it to env parameter

it’s likely that you need to specify the full path to the electron command, since it isn’t on your path.

If you are running your script from your project root, electron is probably at in ./node_modules/.bin/electron, if they packaged up the app to be run that way.

I would guess that your alternative library checks node_modules by default.

The alternative would be to ensure electron is in your path, but that requires updating your system configuration, which it would be weird for a library to do.

Edit: example of call with path:

const childProcess: ChildProcess__type = ChildProcess.spawn(
   'node_modules/.bin/electron',
   [ 'ProjectInitializer__ElectronMain.js' ],
   { cwd: __dirname }
);

I'd also add some dumb logging on the process, so you know why the process failed:

function log(data) {
    console.log("" + data)
}
child_process.stdout.on('data', log)
child_process.stderr.on('data', log)
child_process.on('close', log)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!