Can we launch a node command on a mac without node

2019-03-06 04:32发布

问题:

When I package an electron app using electron-packager. The app spawns a child process which uses a 'node' command. Now if I try to launch my app in a system with no node installed on it, does the app work?

I have been trying to achieve this and facing various issues, the electron community suggested me to use fork method, spawn method with 'Process.execPath' as command and also setting the ELECTRON_RUN_AS_NODE variable but nothing seems to work on my end.

Now after doing all this I question myself, do I definitely need node installed on my system to run the app? or is there really a way that can pass the parent environment(which I believe has node) to the child process? If yes what am I missing here?

Something to note, I am using 'fixpath()' to set the $PATH on macOS when run from a GUI app. Not sure if this is messing up something in my code. https://www.npmjs.com/package/fix-path

Please find my code below:

'use strict'
 const fixPath = require('fix-path');

 let func = () => {
   fixPath();   
   const child = childProcess.exec('node scriptPath --someFlags', {
     detached: true, 
     stdio: 'ignore',
     env: {
       ELECTRON_RUN_AS_NODE: 1,
     }
 });
 child.on('error', (err) => {
   console.log("\n\t\tERROR: spawn failed! (" + err + ")");
 });

 child.stderr.on('data', function(data) {
   console.log('stdout: ' +data);
 });

 child.on('exit', (code, signal) => {
   console.log(code);
   console.log(signal);
 });

 child.unref();
 }

回答1:

Yes, we can run a packaged app which runs a child node process even on a system with no node installed. One can use 'fork' method to run a node process and by setting the ELECTRON_RUN_AS_NODE env variable. Please find the sample code below.

 let func = () => {
   const child = childProcess.fork(path, args, 
   {
     detached: true, 
     stdio: 'ignore',
     env: {
        ELECTRON_RUN_AS_NODE: 1
     }
   }

 });

 child.on('error', (err) => {
   console.log("\n\t\tERROR: spawn failed! (" + err + ")");
 });

 child.on('exit', (code, signal) => {
   console.log(code);
   console.log(signal);
 });

 child.unref();