The fs module included in the Node.js provides different methods to interact with the file system. You can use the fs.open() method 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 it doesn't 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 which means that it will block the Node.js event loop while traversing the file and creating a new file.

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 don't 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.

Last Updated: