Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Writing Files | Section
Node.js Fundamentals

bookWriting Files

Swipe to show menu

Writing files is a fundamental task in Node.js, and you will often need to save data such as logs, notes, or configuration information to disk. Node.js provides the fs (file system) module, which includes methods for writing files both asynchronously and synchronously. When you write to a file, you can either create a new file or overwrite the contents of an existing one. This is an important concept to understand because writing to a file with these methods will replace all the content that was previously in the file.

const fs = require('fs');

fs.writeFileSync('notes.txt', 'My first note');

This code creates a new file called notes.txt in the current directory and writes "My first note" into it. If notes.txt already exists, its entire content will be replaced with the new string. This behavior is important to remember: writing to a file using fs.writeFileSync or fs.writeFile always replaces the existing content of the file.

const fs = require('fs');

fs.writeFile('notes.txt', 'My updated note', (err) => {
  if (err) {
    console.error('Failed to write file:', err);
    return;
  }
  console.log('Note saved!');
});
Note
Note

Key concept: writing to a file using fs.writeFile or fs.writeFileSync will always replace any existing content in that file. If you want to add to the existing content instead, you will need to use a different method.

When you save notes, logs, or any other data to a file in Node.js, understanding the difference between synchronous and asynchronous file writing, as well as the fact that writing will replace previous content, is essential for avoiding accidental data loss and for choosing the right tool for your specific task.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 22

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 1. Chapter 22
some-alt