Write to files in Node.js – writeFile, appendFile and streams

This tutorial will guide you on how to write to files in Node.js, ensuring you have a strong foundation for file manipulation in your applications.
Writing to files is a common task in web development and Node.js makes it convenient to do so with its built-in ‘fs’ (File System) module. Whether you’re looking to create a new file, append to an existing one, or write to it synchronously, Node.js provides you with the functionalities to accomplish these tasks.Write to files in Node.js

 

Setting up Your Environment

Before diving into file operations, ensure that you have Node.js installed on your system. If it’s not installed, download it from the official Node.js website. Once installed, you can use the ‘fs’ module which is included in the Node.js standard library, meaning no additional installation is necessary.

 

Write to Files In Node.js with fs.writeFile

The ‘fs.writeFile’ method is one of the most straightforward approaches for writing to files. It takes three arguments: the file path, the data to write, and a callback function to handle errors or confirm successful writing.

function writeToFile(filename, content) {
  const fs = require('fs');
  fs.writeFile(filename, content, function(err) {
    if (err) {
      return console.error(err);
    }
    console.log('File written successfully');
  });
}
writeToFile('example.txt', 'Hello Node.js File System!');

Output:

File written successfully

Appending Data with fs.appendFile

If you need to add data to an existing file without overwriting its contents, ‘fs.appendFile’ is the method to use.

function appendToFile(filename, content) {
  const fs = require('fs');
  fs.appendFile(filename, content, function(err) {
    if (err) {
      return console.error(err);
    }
    console.log('Data appended successfully');
  });
}
appendToFile('example.txt', '\\nLet\'s append this text!');

Output:

Data appended successfully

Using Write Streams

For dealing with larger files or streams of data, ‘fs.createWriteStream’ should be your preferred method. It allows you to write data incrementally.

function useWriteStream(filename, content) {
  const fs = require('fs');
  let stream = fs.createWriteStream(filename);
  stream.write(content);
  stream.end();
}
useWriteStream('largefile.txt', 'This is a large file with streamed data.');

Output:

(The file 'largefile.txt' is written with streamed data without explicit confirmation)

Write to Files Synchronously

Synchronous file writing is generally not recommended for I/O intensive web applications but can be useful in scripts and simple tasks. The ‘fs.writeFileSync’ method will block the Node.js event loop until the file is written.

function writeFileSync(filename, content) {
  const fs = require('fs');
  try {
    fs.writeFileSync(filename, content);
    console.log('File written synchronously');
  } catch (err) {
    console.error('Error writing file:', err);
  }
}
writeFileSync('sync-example.txt', 'Synchronous write to file.');

Output:

File written synchronously

Error Handling in File Operations

Proper error handling is crucial to avoid crashes and other issues. Callbacks in asynchronous methods and try/catch blocks in synchronous methods help handle exceptions effectively.

References

Conclusion

Write to files in Node.js is a versatile and valuable skill to manage application data. Start with ‘fs.writeFile’ for basic writing, ‘fs.appendFile’ to add content, ‘fs.createWriteStream’ for handling larger data streams, and ‘fs.writeFileSync’ for synchronous operations. By understanding the different methods and practicing proper error handling, you will ensure robust and reliable file operations in your Node.js applications.