13

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.

Community
  • 1
  • 1
oleiba
  • 550
  • 1
  • 4
  • 12
  • 5
    If you packaged your app with electron-builder, there's an `extraResources` option in the `build` section of your package.json that you can use to copy certain files into the resources/app directory, outside of the asar. If you bundle your app with the node.js binary, you can use child process to spawn the scripts in the extra resources directory. –  Jul 03 '17 at 05:50
  • @Bailey Thank you so much!!! Exactly what I was looking for – RyanQuey Mar 12 '18 at 01:11

1 Answers1

7

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.

sanperrier
  • 606
  • 5
  • 12
  • I checked that process.cwd() is not the app dir (...Resources/app.asar) so require.resolve does not work on my end. It will only work when I skipped the asar packing, at the time process.cwd() === (...Resources/app). Acoording to the docs it's the correct behavior I guess? (https://www.electronjs.org/docs/latest/tutorial/asar-archives#working-directory-can-not-be-set-to-directories-in-archive) – addlistener Jun 11 '23 at 12:05