# How to create an empty file in Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 29, 2020, updated Oct 1, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-create-empty-file

> Learn how to use the built-in Node.js file system module to create an empty file.

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:

```javascript
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:

```javascript
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:

```javascript
fs.closeSync(fs.openSync('file.txt', 'w'));
```

That's it. Take a look at how to [read and write files in Node.js](https://attacomsian.com/blog/reading-writing-files-nodejs) to learn more about handling different files in a Node.js application.
