Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js / Delete content in file

Tags:

node.js

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?

like image 352
user937284 Avatar asked Jun 28 '13 18:06

user937284


People also ask

How do I empty a file in node JS?

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.

What is the use of FS unlink () method?

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.

What is Libuv in node JS?

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.

What is delete in node JS?

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.


2 Answers

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.

like image 59
Andbdrew Avatar answered Sep 21 '22 15:09

Andbdrew


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

like image 31
Peter Lyons Avatar answered Sep 21 '22 15:09

Peter Lyons