TOPKAT
TOPKAT

Reputation: 8668

Can a nodeJs script delete his own file?

I'm working on an updater and I wish there is some way for the updater to update itself (remove and copy the new file from which the script is run).

Upvotes: 4

Views: 997

Answers (2)

Marcelo Idemax
Marcelo Idemax

Reputation: 2810

  • Is it possible ? Yes...
  • Is it a good practice ? It depends, if you are updating an application, it could be a good approach...
  • Have you got an advice for such a situation ? Not actually because if you need a new version of your app you must update the files but I would suggest a parallel app who is in charge of updating the main app...

Example:

var fs  = require('fs');

console.log("I'm about to delete myself...");

console.log('clonning myself...');
fs.copyFileSync('./selfDelete.js', './selfDelete_bkp.js');

console.log('removing myself...');
fs.unlinkSync('./selfDelete.js');

console.log('new version of me...');
fs.renameSync('./selfDelete_bkp.js', './selfDelete.js');

Upvotes: 4

Lakshitha Ruwan
Lakshitha Ruwan

Reputation: 959

Not a good practice.

And you cannot update while you running. What I can suggest is you can create a new file somewhere with updates and then replace the current file with the new file from a scheduled task which runs sometime later. Not sure that answered your question but this is what I can think of.

Upvotes: 1

Related Questions