oleiba
oleiba

Reputation: 590

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.

Upvotes: 13

Views: 9083

Answers (1)

sanperrier
sanperrier

Reputation: 634

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.

Upvotes: 8

Related Questions