Skip to content
Advertisement

Execute Powershell script from Node.js with ES6 Modules enabled

I need to execute a Powershell file on my NodeJS server and the answer to that is allready given in this post.

However I am unable to replace const { exec } = require('child_process'); or var spawn = require("child_process").spawn; with the needed Import since my Server is running with ES6 Modules enabled in the package.json "type": "module"

Does anybody know how to properly import the needed Module in this specific case? Here is the code I was trying out on my server which are from the Users Honest Objections and muffel posted in this post:

Honest Objections Code:

const { exec } = require('child_process');
exec('command here', {'shell':'powershell.exe'}, (error, stdout, stderr)=> {
    // do whatever with stdout
})

muffel Code:

var spawn = require("child_process").spawn,child;
child = spawn("powershell.exe",["c:\temp\helloworld.ps1"]);
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

Advertisement

Answer

You can replace CommonJS imports

const { exec } = require('child_process');
var spawn = require("child_process").spawn;

with ES6 imports

import { exec } from 'child_process';
import { spawn } from 'child_process';

at module scope and with

const { exec } = import('child_process');
var spawn = import('child_process').spawn;

at function scope.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement