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
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:
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');
);
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);
}
});
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.