I want to delete the content of a simple text file with node.js. Or replace the file with a new/empty one.
How can I achieve this in node?
Join Stack Overflow to learn, share knowledge, and build your career.
I want to delete the content of a simple text file with node.js. Or replace the file with a new/empty one.
How can I achieve this in node?
You are looking for fs.truncate
or fs.writeFile
Either of the following will work:
const fs = require('fs')
fs.truncate('/path/to/file', 0, function(){console.log('done')})
or
const fs = require('fs')
fs.writeFile('/path/to/file', '', function(){console.log('done')})
There are also synchronous versions of both functions that you should not use.
const fs = require('fs');
and then fs.truncate(filePath, () => { });
. Since it is now available I'd also recommend using const
instead of var
to avoid unwanted side effects in particular if you're working with a larger code base.
– Manfred
Feb 9 '20 at 22:57
fs.unlink is the call you need to delete a file. To replace it with different contents, just overwrite it with fs.writeFile
.