Create an empty file in Node.js?

I am currently using

fs.openSync(filepath, 'a') 

But it is a little complicated. Is there a standard way to create an empty file in Node.js?

+46
filesystems
09 Oct '12 at 10:01
source share
4 answers

If you want the file to be empty, you want to use the 'w' flag instead:

 var fd = fs.openSync(filepath, 'w'); 

This will crop the file if it exists, and create it if it is not.

Wrap it in a fs.closeSync call if you don't need the file descriptor that it returns.

 fs.closeSync(fs.openSync(filepath, 'w')); 
+99
09 Oct
source share
β€” -

https://github.com/isaacs/node-touch will do the job and, like the UNIX tool that it emulates, it won’t overwrite the existing file.

+8
Jul 30 '14 at 5:23
source share

If you want it to be the same as when connecting to UNIX, I would use what you have fs.openSync(filepath, 'a') , otherwise "w" will overwrite the file if it already exists, and "wx" will crash if it already exists. But you want to update the mtime file, so use 'a' and do not add anything.

+5
Dec 14 '15 at 3:06
source share

Here's an asynchronous path using "wx" , so it doesn't work in existing files.

 var fs = require("fs"); fs.open(path, "wx", function (err, fd) { // handle error fs.close(fd, function (err) { // handle error }); }); 
+3
Dec 26 '14 at 17:40
source share



All Articles