Node js child process delete multiple files

1.1k views Asked by At

I'm trying to set up a node.js child process to delete multiple files via the terminal. This works when deleting one file - but fails when I supply an array of files.

const spawnSync = require('child_process').spawnSync;

var toDelete = array.join(' ');

  if (toDelete.length) {    
    spawnSync('rm', ['-rf', toDelete ]);
  }

which I thought would end up being sent as rm -rf data/foo.txt data/bar.txt (which works on when I type it into the terminal)

...however, I must be doing it wrong.

1

There are 1 answers

1
alex On BEST ANSWER

It's because it passes your string as a single argument to rm -rf like if you were typing:

# rm -rf "data/foo.txt data/bar.txt" 

Since spaces are valid characters for a filename in Unix, it tries to remove a single file named "data/foo.txt data/bar.txt"

So, you should directly pass your array:

  if (toDelete.length) {    
    spawnSync('rm', ['-rf'].concat(toDelete));
  }