Unable to require('child_process').spawn, console says spawn is not a function, Python-Shell node package

imyjimmy picture imyjimmy · Jun 23, 2016 · Viewed 10.7k times · Source

I am attempting to use an external package:

npm install [python-shell][1]

Right now, I have just the basic js file with the example the package comes with:

console.log('hey in main.js')
var PythonShell = require('python-shell');

PythonShell.run('./my_script.py', function (err) {
  if (err) throw err;
  console.log('finished running python script');
});

Along with my_script.py, etc

When I start up the server, the console.log says:

Uncaught TypeError: spawn is not a function

Within the index.js of the python-shell package, spawn is required correctly (similar case):

var spawn = require('child_process').spawn;

And later, it is used in the package like so:

this.childProcess = spawn(pythonPath, this.command, options);

However, spawn does seem to be a function:

master$>node
> require('child_process')
{ ChildProcess: 
   { [Function: ChildProcess]
     super_: 
      { [Function: EventEmitter]
        EventEmitter: [Circular],
        usingDomains: true,
        defaultMaxListeners: 10,
        init: [Function],
        listenerCount: [Function] } },
  fork: [Function],
  _forkChild: [Function],
  exec: [Function],
  execFile: [Function],
  spawn: [Function],
  spawnSync: [Function: spawnSync],
  execFileSync: [Function: execFileSync],
  execSync: [Function: execSync] }

So I'm not sure why console says it is not a function.

Answer

Barrard picture Barrard · Jun 20, 2017

I ran into this same problem trying to run code like this

var spawn = require('child_process')
var child = spawn('pwd')

would result in error

 TypeError: spawn is not a function
at Object.<anonymous> (/home/sailor/advancedNode/child_cluster_exec/spawn.js:5:13)

however, adding spawn to the require fixed it

 var spawn = require('child_process').spawn
 var child = spawn('pwd')

OR

      var {spawn} = require('child_process')

this works fine....