0

I would like to delete the files that have appeared in the directory as a side effect of running this piece of code. I have tried the following method but it does not work as when I check if any files with the .csv extension are there they are still present. I have used the following link as a template

http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

My code is:

    process.on('exit', function()
{
    var child = exec('~/.ssh/project' + 'rm *.csv', 
    function (error, stdout, stderr)
    {
        if (error !== null || stderr.length > 0)
        {
            console.log(stderr);
            console.log('exec error: ' + error);
              proces.exit();
        }
    });

});

But this is not working since there are still csv files in this directory

user2811419
  • 1,923
  • 2
  • 14
  • 15

1 Answers1

0

As thefourtheye mentioned "Asynchronous callbacks will not work in exit event". So anything you have to do, will have to be sync. In this case you have two choices:

  1. Use execSync. The good thing about this is that it saves you from a lot of complexity and for a lot of files might be faster(due to concurrency):
process.on('exit', () => 
  execSync('~/.ssh/project rm *.csv');
);
  1. Use fs.readdirSync and fs.unlinkSync. Originally thefourtheye wrote it in his deleted answer. This might be a little faster if there's a one or a few files as it doesn't involve creating a process and lot of other things.
function getUserHome() {
  return process.env[(process.platform==='win32')?'USERPROFILE':'HOME']+path.sep;
}

process.on('exit', () =>
  fs.readdirSync(getUserHome() + ".ssh/project").forEach((fileName) => {
    if (path.extname(fileName) === ".csv") {
      fs.unlinkSync(fileName);
    }
  });
);
Community
  • 1
  • 1
Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115