Question:
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.
psscript.ps1
1 2 3 |
Write-Host "listening for Win32_VolumeChangeEvent"; Register-WmiEvent -Query "SELECT * FROM Win32_VolumeChangeEvent" -Action {Write-Host "something happened"} | Out-Null; |
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
nodescript.js
1 2 3 4 5 6 7 8 9 |
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 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.
1 2 3 4 5 6 7 8 |
C:\myproject>node nodescript.js DATA: listening for Win32_VolumeChangeEvent DATA: psscript closed C:\myproject> |
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.
1 2 3 4 5 |
C:\myproject>node nodescript.js listening for Win32_VolumeChangeEvent PS C:\myproject> something happened something happened |
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
Answer:
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.