Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a nodeJs script delete his own file?

Tags:

node.js

fs

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).

  • Is it possible?
  • Is it a good practice?
  • Have you got an advice for such a situation?
like image 755
TOPKAT Avatar asked Oct 26 '25 10:10

TOPKAT


2 Answers

  • 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');
like image 104
Idemax Avatar answered Oct 29 '25 01:10

Idemax


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.

like image 31
Lakshitha Ruwan Avatar answered Oct 29 '25 02:10

Lakshitha Ruwan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!