executing long running powershell script in nodejs


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


I’m not an expert in powershell but it should just listen on volumeChangeEvent and write something happened when it fires

Nodejs spawns it as child using following code


It should catch anything on child’s stdout and parse it. For demonstration purpose it just prints out with prepended string DATA:.

This is the log. nodescript spawns the psscript and prints its output with the DATA: as i wanted. The problem is that the psscript closes and nodejs exits as well so i will never receive event.

so i was looking for a way to make the powershell not close. I ended up using -noexit argument in spawn var child = spawn('powershell.exe', ['-noexit', script]); which leads to this log.

nodescript spawns the psscript which prints the listening for Win32_VolumeChangeEvent just fine but then it prints PS C:\myproject> (notice the PS). I guess the powershell script registered event listener and then closed (hence the PS C:\myproject>) but powershell was still running (hence the something happened) as well as node. It’s confusing fo me because I’m just used to the way node deals with event listeners (node never closes when any listenner is attached). Anyway the powershell script keeps on listening and notifying. That’s the twice printed something happened because I plugged in and out the flash drive.

That 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 output of the powershell while it never outputs it to the child.stdout and child.stdout.on('data', ...) never receives any data. As you can see in the second log there’s no DATA:.
So I’m unable to work with it

Thank you for your help


To keep Node running – uou can just add a while(true) {} statement after your code snippet.

To have your node instance eventually timeout, you can use setTimeout and call process.exit() when timeout has expired.


executing long running powershell script in nodejs by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply