0

I have following code, its result is "Expected number is: undefined", why the process.env.number is undefined, it should be 123, what's wrong with the code? Please help out, thanks!

var exec = require('child_process').exec;
var exec2 = require('child_process').exec;
exec('ls ', {env: {number: 123}}, function(err, stdout, stderr) {
  if (err) { throw err; }
  console.log('stdout:\n', stdout);
  console.log('stderr:\n', stderr);
  exec2('ps -ef ', function(err, stdout, stderr) {
     console.log("   Expected number is:   " + process.env.number);
  });
});
john
  • 1
  • 2
  • it sets env variable for child process and you are checking in parent process – vkurchatkin May 23 '14 at 10:33
  • thanks, is exec2 not the child process of exec? – john May 23 '14 at 15:40
  • Why do you require child_process.exec two times? It returns exactly the same function since required node_modules are cached so they are loaded just once even if you require them from different files. – Enrique Fueyo May 23 '14 at 15:44
  • @john [According to the docs](http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback), the callback for `exec` runs *after* the child process has terminated. You set the `number` environment variable for the `ls` execution, and then, in the `exec` callback, *after the `ls` call has terminated*, you run `ps -ef`. – apsillers May 23 '14 at 15:50
  • thanks, ls is exactually terminated before running ps -ef, so process.env.number is undefined. – john May 23 '14 at 16:04

0 Answers0