Node.js – Create File using Node FS

We can create a new file in Node.js using Node fs module.

In this tutorial, we shall learn to create a File in Node.js using Node FS (File System) built-in module. Node.js example programs that use writeFile(), appendFile() or open() function are provided.

The examples use the CommonJS require() syntax, which is still common in beginner Node.js programs. You will also see when a file is overwritten, when content is appended, and how to create a file safely without replacing an existing one.

Node.js fs methods used to create a file

Node.js provides different file system methods for different creation needs. Before choosing a method, decide whether you want to write fresh content, append content, or open a file with a specific file mode.

Node FS methodCreates file if missing?If file already existsBest used for
fs.writeFile()YesOverwrites content by default.Creating a file with complete content.
fs.appendFile()YesAdds content at the end.Logs, records, and repeated additions.
fs.open()Depends on open modeDepends on open modeLow-level control with file flags.

Syntax – writeFile() function

The syntax of fs.writeFile() function is

</>
Copy
fs.writeFile('<fileName>',<contenet>, callbackFunction)

A new file is created with the specified name. After writing to the file is completed (could be with or without error), callback function is called with error if there is an error reading file.

If a file already exists with the name, the file gets overwritten with a new file. Care has to be taken while using this function, as it overwrites existing file.

Syntax – appendFile() function

The syntax of fs.appendFile() function is

</>
Copy
fs.appendFile('<fileName>',<contenet>, callbackFunction)

If the file specified in the appendFile() function does not exist, a new file is created with the content passed to the function.

Syntax – open() function

The syntax of fs.open() function is

</>
Copy
fs.open('<fileName>',<file_open_mode>, callbackFunction)

If the specified file is not found, a new file is created with the specified name and mode and sent to the callback function.

Steps – Create a File in Node.js

Following is a step by step guide to create a new File in Node.js :

Step 1 : Include File System built-in module to your Node.js program

</>
Copy
var fs = require('fs');

Step 2 : Create file using one the methods mentioned above. Following are the examples demonstrating to create a file in Node.js with each of these methods.

Example 1 – Create File using writeFile()

In this example, we will use writeFile() function and create a file named newfile.txt.

createFileExample.js

</>
Copy
// include node fs module
var fs = require('fs');

// writeFile function with filename, content and callback function
fs.writeFile('newfile.txt', 'Learn Node FS module', function (err) {
  if (err) throw err;
  console.log('File is created successfully.');
}); 

Run the program using node command in terminal or command prompt.

Output

$ node createFileExample.js
File is created successfully.

The file should be created next to your example node.js program with the content ‘Learn Node FS module’.

Example 2 – Create File using appendFile()

In this example, we will use appendFile() function and create a file named newfile_2.txt.

createFileExample2.js

</>
Copy
// include node fs module
var fs = require('fs');

// appendFile function with filename, content and callback function
fs.appendFile('newfile_2.txt', 'Learn Node FS module', function (err) {
  if (err) throw err;
  console.log('File is created successfully.');
}); 

Run the program using node command in terminal or command prompt.

Output

$ node createFileExample2.js
File is created successfully.

The file should be created next to your example node.js program with the content ‘Learn Node FS module’.

Example 3 – Create File using open()

In this example, we will use open() function and create a file named newfile_3.txt.

createFileExample3.js

</>
Copy
// include node fs module
var fs = require('fs');

// open function with filename, file opening mode and callback function
fs.open('newfile_3.txt', 'w', function (err, file) {
  if (err) throw err;
  console.log('File is opened in write mode.');
}); 

Run the program using node command in terminal or command prompt.

Output

$ node createFileExample3.js
File is opened in write mode.

The file should be opened in write mode.

Create a file in Node.js without overwriting an existing file

By default, fs.writeFile() replaces the file content if the file already exists. To create a file only when it is missing, pass the wx flag. If the file exists, Node.js returns an EEXIST error instead of overwriting it.

createFileOnlyIfMissing.js

</>
Copy
const fs = require('fs');

fs.writeFile('safe-newfile.txt', 'Created only if missing.', { flag: 'wx' }, function (err) {
    if (err) {
        if (err.code === 'EEXIST') {
            console.error('File already exists.');
            return;
        }

        console.error('Could not create file:', err.message);
        return;
    }

    console.log('File created safely.');
});
File created safely.

Create a file inside a folder using path.join()

A relative file name such as 'newfile.txt' is resolved from the current working directory of the Node.js process. To build a reliable path relative to the JavaScript file, use __dirname with the built-in path module.

createFileInFolder.js

</>
Copy
const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'output', 'report.txt');

fs.writeFile(filePath, 'Report content', 'utf8', function (err) {
    if (err) {
        console.error('Could not create file:', err.message);
        return;
    }

    console.log('File created at:', filePath);
});

The folder in the path must exist. If the folder may be missing, create it first before calling writeFile().

Create the parent directory before creating a Node.js file

If the target directory does not exist, file creation fails with an ENOENT error. The following example creates the folder first and then writes the file.

</>
Copy
const fs = require('fs');
const path = require('path');

const folderPath = path.join(__dirname, 'output');
const filePath = path.join(folderPath, 'notes.txt');

fs.mkdir(folderPath, { recursive: true }, function (mkdirErr) {
    if (mkdirErr) {
        console.error('Could not create folder:', mkdirErr.message);
        return;
    }

    fs.writeFile(filePath, 'Node.js file created inside output folder.', 'utf8', function (writeErr) {
        if (writeErr) {
            console.error('Could not create file:', writeErr.message);
            return;
        }

        console.log('Folder and file are ready.');
    });
});

Create a file in Node.js using fs/promises

Modern Node.js programs often use promises with async and await. You can create a file with fs/promises and handle errors in a try...catch block.

</>
Copy
const fs = require('fs/promises');

async function createFile() {
    try {
        await fs.writeFile('promise-file.txt', 'Created with fs/promises.', 'utf8');
        console.log('File created successfully.');
    } catch (err) {
        console.error('Could not create file:', err.message);
    }
}

createFile();

Node.js file open modes for fs.open()

The file open mode controls how fs.open() behaves. Some commonly used modes are shown below.

ModeMeaningImportant behavior
wOpen for writing.Creates the file if missing and truncates it if it exists.
wxOpen for exclusive writing.Fails if the file already exists.
aOpen for appending.Creates the file if missing and writes at the end.
axOpen for exclusive appending.Fails if the file already exists.
rOpen for reading.Fails if the file does not exist.

For simple file creation with content, fs.writeFile() is usually easier than manually opening and managing a file descriptor.

Common Node FS errors while creating files

Error or symptomLikely reasonFix
ENOENT: no such file or directoryThe target folder does not exist or the path is wrong.Create the folder first and check the path.
EEXIST: file already existsYou used an exclusive mode such as wx.Choose a new file name or handle the existing file.
EACCES: permission deniedThe process cannot write to that folder.Use a writable folder or correct the permissions.
Existing content disappearswriteFile() or w mode replaced the file content.Use appendFile(), a, or wx depending on the requirement.

FAQs on creating files in Node.js using fs

How to create a file in Node.js using Node fs module?

Import the built-in fs module with require('fs') and call fs.writeFile(fileName, content, callback). If the parent folder exists and the process has permission, Node.js creates the file.

Does fs.writeFile() create a file if it does not exist?

Yes. fs.writeFile() creates the file when it is missing. If the file already exists, it overwrites the existing content by default.

How do I create a file in Node.js without overwriting it?

Use fs.writeFile() with an exclusive flag such as { flag: 'wx' }. If the file already exists, Node.js returns an EEXIST error.

What is the difference between writeFile() and appendFile() in Node.js?

writeFile() writes complete content and overwrites by default. appendFile() adds content to the end of the file and creates the file if it is missing.

Why does Node.js show ENOENT while creating a file?

ENOENT usually means the directory in the file path does not exist or the path is incorrect. Create the directory first or correct the file path.

Editorial QA checklist for this Node.js create file tutorial

  • Confirm that writeFile(), appendFile(), and open() are explained with their creation behavior.
  • Check that overwrite behavior is clearly stated for fs.writeFile() and w mode.
  • Verify that new examples handle errors before printing success messages.
  • Ensure the path guidance explains parent folders and path.join().
  • Confirm that safe creation with wx and common errors such as ENOENT, EEXIST, and EACCES are covered.

Summary: creating files in Node.js with Node FS

In this Node.js Tutorial – Node FS, we have learnt to create a File in Node.js using Node FS (File System) module.

Use fs.writeFile() to create a file with complete content, fs.appendFile() to create or append content, and fs.open() when you need a specific file open mode. When existing files must not be replaced, use an exclusive flag such as wx.