Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a node.js script in packaged electron app

In electron packaged app, I am trying to execute a server file from a node_modules dependency. From the main process, I'm trying something like:

var cp = require('child_process')
cp.execFile('node', path.join(__dirname, 'node_modules/my-module/server.js'))

I see the server is launched as expected when launching my app from my local command-line, but not when packaged as asar. What is the right way to achieve that?

Notes:
I have looked into https://electron.atom.io/docs/tutorial/application-packaging/#executing-binaries-inside-asar-archive:

There are Node APIs that can execute binaries like child_process.exec, child_process.spawn and child_process.execFile, but only execFile is supported to execute binaries inside asar archive.

Also, saw this SO answer: Executing a script inside an ASAR archive which says I need to require my script - however, I think it's wrong. This actually spawns this script within the same process (once required) and not when performing execFile.

like image 279
oleiba Avatar asked May 15 '17 13:05

oleiba


1 Answers

You don't need to bundle node with electron. Just make sure your 'node_modules/my-module/server.js' is packaged in asar and use

cp.fork(path.resolve(__dirname, 'node_modules/my-module/server.js'))

or

cp.fork(require.resolve('my-module/server.js'))

it should work just fine.

This way electron will use bundled node, add transparent asar support to it and run script from asar archive.

If you cp.execFile('node'... you will use outside node, that doesn't support asar.

like image 62
sanperrier Avatar answered Nov 09 '22 06:11

sanperrier