Create an empty file in Node.js?


Question

For now I use

fs.openSync(filepath, 'a')

But it's a little tricky. Is there a 'standard' way to create an empty file in Node.js?

1
65
12/11/2016 9:29:38 AM

Accepted Answer

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

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

That will truncate the file if it exists and create it if it doesn't.

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

fs.closeSync(fs.openSync(filepath, 'w'));
132
12/16/2014 1:57:26 PM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon