Node.js / Delete content in file

node.js

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

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.

Solution 2 - node.js

fs.unlink is the call you need to delete a file. To replace it with different contents, just overwrite it with fs.writeFile.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser937284View Question on Stackoverflow
Solution 1 - node.jsAndbdrewView Answer on Stackoverflow
Solution 2 - node.jsPeter LyonsView Answer on Stackoverflow