Home > Back-end >  Node: spawn a command and print results to a file
Node: spawn a command and print results to a file

Time:12-09

If I want to list the files of a directory and save the results in a res.txt I can run the command

ls -l > res.txt

Now I would like to do the same in a process spawned from the main process of Node.

I have tried naively this

spawn(
  'ls',
  ['-l', '>', 'res.txt'],
);

but does not work. Is there any way to achieve what i want?

CodePudding user response:

After some more googling I found that the shell: true option does the trick.

So, if I want a spawned process to run a command which streams its output to a file, I can use this approach

spawn(
  'ls -l > res.txt',
  [],
  {shell: true}
);

CodePudding user response:

so from the node documentation, which can be found here:

https://nodejs.org/api/child_process.html#child_processspawncommand-args-options

const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
  • Related