Executing long running powershell script in nodejs

In my nodejs project, I need to detect when a USB flash drive is plugged in / out. I decided to use powershell script and run it using child_process exec or spawn.

psscript.ps1

Write-Host "listening for Win32_VolumeChangeEvent";
Register-WmiEvent -Query "SELECT * FROM Win32_VolumeChangeEvent" -Action {Write-Host "something happened"} | Out-Null;

      

I'm not a powershell expert, but it should just listen for volumeChangeEvent and write something happened

when it runs

Nodejs spawns it as a child using the following code

nodescript.js

var spawn = require('child_process').spawn;
var child = spawn('powershell.exe', ['psscript.ps1']);
child.stdout.on('data', function(data){
    console.log('DATA:', data.toString());
});
child.stdout.on('close', function(data){
    console.log('psscript closed');
});

      

It has to catch anything on the child stdout and parse it. For demo purpose, it just prints with the line appended DATA:

.

This is a magazine. nodecript runs psscript and prints its output using the DATA:

way I wanted. The problem is psscript gets closed and nodejs also exits, so I never get the event.

C:\myproject>node nodescript.js
DATA: listening for Win32_VolumeChangeEvent
DATA:

psscript closed

C:\myproject>

      

so I was looking for a way to make powershell not close. I ended up using an argument -noexit

in spawn var child = spawn('powershell.exe', ['-noexit', script]);

that leads to this log.

C:\myproject>node nodescript.js
listening for Win32_VolumeChangeEvent
PS C:\myproject> something happened
something happened

      

nodescript spawns psscript, which prints listening for Win32_VolumeChangeEvent

just fine, but then prints PS C:\myproject>

(note PS

). I suppose the powershell script registered an event listener and then closed (hence PS C:\myproject>

), but powershell was still working (hence something happened

) as well as node. This is confusing me because I'm just used to the way node deals with event listeners (a node never closes when any listener is connected). Anyway, the powershell script keeps listening and notifying. It's printed twice something happened

because I plugged in and unplugged my USB stick.

This is pretty much what I want, but the problem is that the child spawned with -noexit

takes over my nodejs console and pollutes it with powershell output, while it never outputs it to child.stdout

and child.stdout.on('data', ...)

never gets any data. As you can see in the second magazine, no DATA:

. Therefore, I cannot work with him.

thanks for the help

+3


source to share


1 answer


To keep Node , you can simply add a statement while(true) {}

after the code snippet.



To make your node instance end up timeout , you can use setTimeout

and call process.exit()

when the timeout has expired.

0


source







All Articles