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.

2
  • 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. Commented Jul 3, 2017 at 5:50
  • @Bailey Thank you so much!!! Exactly what I was looking for Commented Mar 12, 2018 at 1:11

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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? (electronjs.org/docs/latest/tutorial/…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.