The fs
module in Node.js provides different methods to interact with the file system. You can use the fs.open()
function to asynchronously create a new file in Node.js.
Here is an example:
const fs = require('fs')
// create an empty file
fs.open('file.txt', 'w', (err, file) => {
if (err) {
throw err
}
console.log('File is created.')
})
The fs.open()
method returns a file descriptor as a second parameter of the callback method. The w
flag ensures that the file is created if does not already exist. If the file already exists, fs.open()
overwrites it and removes all its content.
Note: You should use the
a
flag to avoid overwriting the file content if it already exists.
You can also use the fs.openSync()
method to create an empty file in Node.js. This method is synchronous and will block the Node.js event loop execution until a new file is created.
Here is another example that creates an empty file synchronously:
const fs = require('fs')
// create an empty file
try {
const file = fs.openSync('file.txt', 'w')
console.log('File is created.')
} catch (error) {
console.log(error)
}
If you do not need the file descriptor for further processing, just wrap the call in fs.closeSync()
to close the file automatically:
fs.closeSync(fs.openSync('file.txt', 'w'));
That's it. Take a look at how to read and write files in Node.js to learn more about handling different files in a Node.js application.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.