Search code examples
node.jsspawn

Executing bash script with spawn node.js method returns errors


I cannot find a way to execute my node command with spawn method. My script is :

node node_modules/.bin/webpack-dev-server --port 8081 --content-base app

I tried to execute it like :

spawn('node', ['node_modules/.bin/webpack-dev-server --port 8081 --content-base app']);

this returns an error

Cannot find module '/Users/myuser/code/gui/node_modules/.bin/webpack-dev-server --port 8081 --content-base app'

I also tried this :

spawn('node', ['node_modules/.bin/webpack-dev-server',' --port 8081 ', '--content-base app']);

it runs my webpack server but it doesn't take the port and content-base params into account. For this case the error is :

ERROR in Entry module not found: Error: Cannot resolve module ' --port 8081 '

Any ideas? Thanks!

Oh, and I forgot to add that the script runs well with the exec method.


Solution

  • You have extra spaces in your second argument in the second example. Try this:

    const args = [
      'node_modules/.bin/webpack-dev-server',
      '--port',
      '8081',
      '--content-base',
      'app'
    ];
    spawn('node', args);