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?
In Node. js, you can use the fs. unlink() method provided by the built-in fs module to delete a file from the local file system.
The fs. unlink() method is used to remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.
libuv is a multi-platform C library that provides support for asynchronous I/O based on event loops. It supports epoll(4) , kqueue(2) , Windows IOCP, and Solaris event ports. It is primarily designed for use in Node. js but it is also used by other software projects.
Delete DocumentTo delete a record, or document as it is called in MongoDB, we use the deleteOne() method. The first parameter of the deleteOne() method is a query object defining which document to delete.
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.
fs.unlink is the call you need to delete a file. To replace it with different contents, just overwrite it with fs.writeFile
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With