How to Save Text to a File in Node.js

When working with Node.js, there may be instances when you want to save text or data to a file. This could be for logging, configuration, or storing results. This quick guide will show you how to achieve this using Node.js's built-in fs module in Node.js.

fs.writeFile() Method

The fs.writeFile() method asynchronously writes the provided data to a file. If the file already exists, it is overwritten by default. The functionality can be altered using the 'options' argument.

How to Example

Here's a very simple example of writing to a .txt file.

Let's create a file called saveText.js with the following:

// saveText.js
import fs from 'node:fs';

// Sample text to write to the file
const textToSave = "Hello, Codú!";

// Use the writeFile method
fs.writeFile('output.txt', textToSave, (err) => {
    if (err) throw err;
    // Logging to confirm the file has been saved. 
    console.log('Text has been saved!');
});

Then we can run this script with:

node saveText.js

After executing the script, you should see an output.txt file in your project directory with the content "Hello, Codú!".

Syntax:

fs.writeFile( file, data, options, callback )

Parameters

The method takes four arguments, detailed as follows:

file: Represents the file path where the data will be written. Acceptable types include strings, Buffers, URLs, or file descriptor integers.

data: The content you wish to write to the file. This can be a string, Buffer, TypedArray, or DataView.

options:

An optional string or object that adjusts how the data is written. It has three sub-parameters:

  • encoding: Specifies the file's encoding, defaulting to 'utf8'.
  • mode: An integer that sets the file mode, with a default of 0o666.
  • flag: Determines the flag used when writing, defaulting to 'w'. As there are a few flags you can use you can check the documentation here.

callback: A function that's invoked upon the method's completion. If there is an error, the function will have a single error parameter passed to it. As shown in the example above, this can be used to show that there were no problems with writing to the file.

Notes

writeFile will overwrite the file if it already exists. If you wish to append to an existing file, consider using fs.appendFile.

The fs module also offers synchronous methods (e.g., fs.writeFileSync). However, in many cases, it's recommended to use asynchronous methods to avoid blocking the event loop.


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

Nodejs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.