0

Hello I am trying to run terminal commands from NodeJS and am trying to use the spawn command, I had been using exec but am trying spawn now for the stdout.

All the examples I've bene reading, like this one: Exec : display stdout "live"

Use commands with multiple arguments, like in the example above, the command they run with spawn is :

var spawn = require('child_process').spawn, ls = spawn('ls', ['-lh', '/usr']);

Which is '$ ls -lh /usr'

I am trying to just run the command 'pwd' with no args, but all the ways I've been trying to do so (like below) have resulted in an '' error

var spawn = require('child_process').spawn, ls = spawn('pwd');

or

var spawn = require('child_process').spawn, ls = spawn('pwd', []);

stderr: usage: pwd [-L | -P]
Martin
  • 1,336
  • 4
  • 32
  • 69

1 Answers1

1

Providing arguments in spawn is not mandatory. In your question, spawn is working and and that's why the error you see is actually the output of stderr after spawn('pwd') has been executed.

Working example of pwd with spawn:

var spawn = require('child_process').spawn;

const pwd = spawn('pwd');

pwd.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

pwd.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

pwd.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

Demo: https://repl.it/repls/AlienatedTidyDatalogs

Shumail
  • 3,103
  • 4
  • 28
  • 35