6

I am experimenting with node.js. Trying to spawn processes but cannot seem to get the right PID back on close. If i run the function below it will spawn a process but the returning ls.pid in the on close function will always be the pid from the last process.

function app_cmd(cmd, args,path) {
  ls = spawn ( cmd , args , { cwd : path } );
  console.log ( cmd +' ' + ls.pid );
  ls.on ( 'close' , function(code) {
    console.log ( 'returning: ' + code + ' on ' + ls.pid );
  } );
  return ls.pid;
}

So if i call the function twice i get the following output (note the two times 6940 in the return):

php.exe 6076
php.exe 6940
returning: 0 on 6940
returning: 0 on 6940

Anyone has a pointer for me on how to get the proper PID back in the onClose?

Much appreciated,

Ties

Ties Vandyke
  • 154
  • 1
  • 8
  • 1
    Well written question with a rep of 1. Thanks! – Randy Casburn Apr 03 '18 at 18:55
  • 1
    this is just another flavor of https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example where instead of a loop doing the work, you're calling the function twice. Ensuring that the variable being used isn't shared between calls resolves the issue. – Kevin B Apr 03 '18 at 19:04

1 Answers1

3

It looks like you're declarling ls as a global by mistake causing it to be overwritten the second time, adding a var|let|const should fix it.

function app_cmd(cmd, args,path) {
  const ls = spawn ( cmd , args , { cwd : path } );
  console.log ( cmd +' ' + ls.pid );
  ls.on ( 'close' , function(code) {
    console.log ( 'returning: ' + code + ' on ' + ls.pid );
  } );
  return ls.pid;
}
generalhenry
  • 17,227
  • 4
  • 48
  • 63
  • Perfect solution.. works as a train. I looked my butt of for a global declaration but could not find it in the code. ls is quite common variable declaration so maybe somewhere in the sub libs. Making the object a constance solved everything. – Ties Vandyke Apr 03 '18 at 19:40