How to create an empty file in Node.js

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.