Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an empty file in Node.js?

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?

like image 719
Lai Yu-Hsuan Avatar asked Oct 09 '12 22:10

Lai Yu-Hsuan


People also ask

How do you create an empty file?

From within Windows, right-click in the area you want to create the file. For example, right-click the desktop to create a new text file on the desktop. In the drop-down menu that appears, select New and choose Text Document.

How do I create an empty file in FS?

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.


1 Answers

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')); 
like image 181
JohnnyHK Avatar answered Nov 06 '22 05:11

JohnnyHK