简体   繁体   中英

child_process module has not been loaded yet

I'm looking into NodeJS for running a PowerShell script from my JavaScript script. This is the code I found online:

var spawn = require("child_process").spawn,child;

child = spawn("powershell.exe",["c:\\test\\mypstest.ps1 -arg1 1"]);

child.stdout.on("data",function(data){
    console.log("Powershell Data: " + data);
});

child.stderr.on("data",function(data){
    console.log("Powershell Errors: " + data);
});

child.on("exit",function(){
   console.log("Powershell Script finished");
});

child.stdin.end(); //end input

When I run a live server on the html, I get the following console error:

Uncaught Error: Module name "child_process" has not been loaded yet for context: _. Use require([])

When I change

var spawn = require("child_process").spawn,child;

to

var spawn = require(["child_process"]).spawn,child;

I get the following error:

Uncaught TypeError: spawn is not a function               index.js
Uncaught Error: Script error for "child_process"          require.js

I was under the impression that child_process.js was included in the Node.js installation. How can I fix this?

Not sure why that module hasn't been loaded yet, but you're using the require function incorrectly.

See the docs .

When you supply an array to require , it is going to use the async version of require , and you need to supply a callback that will receive the loaded module.

Try something like this:

require(["child_process"], function (cp) {
    var spawn = cp.spawn;
    // ... use spawn()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM