Last updated: Apr 5, 2024
Reading timeยท5 min
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.
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');
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 you don't want to truncate the file if it already exists, use the a
flag.
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.
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()
.
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 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
.
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.
fs-extra
package.fs.open()
method to create an empty file in Node.jsYou can also use the fs.open()
method to create an empty file in Node.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 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.
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:
This is useful when you don't want to truncate the file at the specified path if it already exists.
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.
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 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
.
const fd = await fs.open(filePath, 'wx');
If an error occurs in the try
block, it gets passed to the catch()
method.
fs-extra
packageYou 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.
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.
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 ensureFile
method ensures the file exists.
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.
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.
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 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.
You can learn more about the related topics by checking out the following tutorials: