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

人走茶凉 提交于 2019-12-23 17:50:13

问题


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.


回答1:


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....




回答2:


Use this under Windows:

const cp = require('child_process');
const cmd = cp.spwan('cmd');
cmd.on('exit',(data)=>{
  console.log(data);
});

spawn is not a "normal" function as usual, it has no default name string like the others.



来源:https://stackoverflow.com/questions/38001720/unable-to-requirechild-process-spawn-console-says-spawn-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!