How to create an empty file in Node.js

Explore how to create an empty file in the file system folder of Node.js

methodfs.openSync()Provided by thefsBuilt-in modules are the best way.

It returns a file descriptor:

const fs = require('fs')
const filePath = './.data/initialized'

const fd = fs.openSync(filePath, ‘w’)

ThiswThe flag ensures that the file is created (if it does not exist), and if the file exists, it is overwritten with the new file and its contents are overwritten.

useaSign to avoid overwriting. If it does not exist, the file will still be created.

If you don’t need a file descriptor, you can wrap the call infs.closeSync()Call to close the file:

const fs = require('fs')
const filePath = './.data/initialized'

fs.closeSync(fs.openSync(filePath, ‘w’))

Download mine for freeNode.js manual


More node tutorials: