How to create an empty file in Node.js
By Flavio Copes
Learn how to create an empty file in Node.js using fs.openSync() with the w flag, and how to wrap it in fs.closeSync() when you do not need the descriptor.
The method fs.openSync() provided by the fs built-in module is the best way to create an empty file in Node.js. It’s the equivalent of the Unix touch command.
Empty files are more useful than they sound. I use them as marker files: a file named initialized whose presence tells the app a setup script already ran. The content doesn’t matter, only the fact that the file exists.
Creating the file
fs.openSync() opens the file, creating it if needed, and returns a file descriptor:
const fs = require('fs')
const filePath = './.data/initialized'
const fd = fs.openSync(filePath, 'w')
the w flag makes sure the file is created if not existing, and if the file exists it overwrites it with a new file, overriding its content.
Use the a flag to avoid overwriting. The file is still created if not existing, and if it exists its content stays untouched.
There’s also the wx flag, which creates the file but throws an error if it already exists. Handy when overwriting would be a bug.
Close the file descriptor
A file descriptor is a number the operating system uses to track the open file. The OS limits how many files a process can keep open, so leaking descriptors in a long-running app eventually causes an EMFILE: too many open files error.
If you don’t need the file descriptor, you can wrap the call in a fs.closeSync() call, to close the file:
const fs = require('fs')
const filePath = './.data/initialized'
fs.closeSync(fs.openSync(filePath, 'w'))
An alternative
fs.writeFileSync() also creates an empty file if you pass an empty string, and it closes the file for you:
fs.writeFileSync('./.data/initialized', '')
Like the w flag, this truncates the file if it already exists.
Watch out for missing folders
One pitfall: the folder must already exist. If ./.data is not there, fs.openSync() throws:
Error: ENOENT: no such file or directory, open './.data/initialized'
Create the folder first:
fs.mkdirSync('./.data', { recursive: true })
The recursive: true option creates any missing parent folders, and doesn’t complain if the folder is already there.
Related posts about node: