How to create an empty file in Node.js [4 easy Ways]

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
5 min

banner

# Table of Contents

  1. How to create an empty file in Node.js
  2. Using the fs.open() method to create an empty file in Node.js
  3. Using the async/await syntax to create an empty file in Node.js
  4. Create an empty file in Node.js using the fs-extra package

# How to create an empty file in Node.js

You can use the fs.openSync() method to create an empty file in Node.js.

When the fs.openSync() method is called with a mode of w, the file is opened for writing.

The file is created if it doesn't exist or truncated if it already exists.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs') const filePath = './my-file.txt'; const fd = fs.openSync(filePath, 'w');

create empty file in node js

The code for this article is available on GitHub

The fs.openSync method returns an integer that represents the file descriptor.

The first argument the method takes is a file path and the second is the flag.

The w flag means that the file is opened for writing.

If the file doesn't exist, it is created, otherwise, the file is truncated if it already exists.

If you don't want to truncate the file if it already exists, use the a flag.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs') const filePath = './my-file.txt'; const fd = fs.openSync(filePath, 'a');

The wx flag is like w but it fails if the file already exists.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs') const filePath = './my-file.txt'; try { // ๐Ÿ‘‡๏ธ using `wx` flag const fd = fs.openSync(filePath, 'wx'); } catch (err) { // ๐Ÿ‘‡๏ธ EEXIST: file already exists, open './my-file.txt' console.log(err.message); }

If you don't need to use the file descriptor that is returned from the fs.openSync() method, wrap the call to the method in fs.closeSync().

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs') const filePath = './my-file.txt'; fs.closeSync(fs.openSync(filePath, 'w'));
The code for this article is available on GitHub

The fs.closeSync() method closes the file descriptor and returns undefined.

If you need to create an empty path in a subdirectory, make sure the subdirectory exists.

For example, the following code sample creates a my-file.txt in a directory called my-folder.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs') const filePath = './my-folder/my-file.txt'; fs.closeSync(fs.openSync(filePath, 'w'));

Make sure the my-folder directory exists before running the Node script.

If you need to create the directories if they don't exist, use the code sample from the subheading that uses the fs-extra package.

# Using the fs.open() method to create an empty file in Node.js

You can also use the fs.open() method to create an empty file in Node.js.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs') const filePath = './my-file.txt'; fs.open(filePath, 'w', (err, fd) => { if (err) { console.log(err.message); } fs.close(fd, err => { if (err) { console.log(err.message); } }); });
The code for this article is available on GitHub

The fs.open() method opens a file asynchronously.

The w flag means that the file is opened for writing.

If the file doesn't exist, it is created, otherwise, the file is truncated if it already exists.

The callback function we passed to fs.open() gets called with an error if one occurred and a file descriptor.

The file descriptor can be used to close the file.

As previously noted, if the file already exists, it would get truncated.

If you don't want to delete the contents of the file if it already exists, use the wx flag.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs') const filePath = './my-file.txt'; fs.open(filePath, 'wx', (err, fd) => { if (err) { console.log(err.message); } });

Notice that we set the flag to wx.

The wx flag is like w but it fails if the path already exists.

If I run the node index.js command, I get back the following message:

  • EEXIST: file already exists, open './my-file.txt'

eexist file already exists open

This is useful when you don't want to truncate the file at the specified path if it already exists.

# Using the async/await syntax to create an empty file in Node.js

When writing more modern code, you might want to use the async/await syntax to create an empty file in Node.js

Here is an example.

index.js
import fs from 'fs/promises'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs') async function createEmptyFile(filePath) { try { const fd = await fs.open(filePath, 'w'); // ๐Ÿ‘‡๏ธ closes the file handle await fd.close(); console.log('empty file created ๐ŸŽŠ'); } catch (err) { console.log(err.message); } } const filePath = './my-file.txt'; createEmptyFile(filePath).then(() => { console.log('Runs after the creation of the empty file'); });
The code for this article is available on GitHub

The createEmptyFile function takes a file path and asynchronously creates an empty file at the specified path.

If the file already exists, it gets truncated (its contents get deleted).

If you don't want to truncate the file if it exists, set the flag to wx.

index.js
const fd = await fs.open(filePath, 'wx');

If an error occurs in the try block, it gets passed to the catch() method.

# Create an empty file in Node.js using the fs-extra package

You can also use the fs-extra package to create an empty file in Node.js.

First, open your terminal in your project's root directory and make sure you have the fs-extra package installed.

shell
npm init -y # install using NPM npm install fs-extra # install using YARN yarn add fs-extra

You can create an empty file using the ensureFile method.

index.js
import fs from 'fs-extra'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs-extra') async function createEmptyFile(filePath) { try { await fs.ensureFile(filePath); console.log('empty file created!'); } catch (err) { console.error(err); } } createEmptyFile('./my-folder/my-file.txt').then(() => { console.log('This runs after the file has been created'); });
The code for this article is available on GitHub

The ensureFile method ensures the file exists.

If the specified file path is in directories that don't exist, these directories are created.

If the file already exists, it is not modified.

The fs.ensureFile method is especially useful when one or more of the directories in the specified file path might not exist.

The example above uses async/await, however, you can also use the .then syntax.

index.js
import fs from 'fs-extra'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs-extra') fs.ensureFile('./my-file.txt') .then(() => { console.log('empty file created'); }) .catch(err => { console.log(err.message); });

You can also call the ensureFileSync() method if you want to create an empty file synchronously.

index.js
import fs from 'fs-extra'; // ๐Ÿ‘‡๏ธ if you use the CommonJS require() syntax // const fs = require('fs-extra') async function createEmptyFile(filePath) { try { fs.ensureFile(filePath); console.log('empty file created!'); } catch (err) { console.error(err); } } createEmptyFile('./my-folder/my-file.txt');
The code for this article is available on GitHub

The only parameter the ensureFileSync() method takes is the file path.

The method ensures that the file exists.

If the specified file path is located in directories that don't exist, these directories are created.

If the file already exists, it is not modified.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev