Course contentsShow
← JavaScript
Lesson 1520 of 2,72333. JavaScript in Node.jsFree lesson

Writing Files with fs.writeFile()

Creating or overwriting files asynchronously with string or buffer content.

Writing Files with fs.writeFile()

You'll learn how to create new files or overwrite existing ones asynchronously using Node.js's file system module.

The Core Idea

fs.writeFile() is the asynchronous method for writing data to files in Node.js. Think of it like saving a document: you tell Node.js what file to create (or replace) and what content to put in it, then Node.js handles the actual disk operation in the background without blocking your program.

Basic Syntax

const fs = require('fs');

fs.writeFile('output.txt', 'Hello, World!', (err) => {
  if (err) {
    console.error('Error writing file:', err);
  } else {
    console.log('File written successfully!');
  }
});

The method takes three arguments:

  1. Path: The file name or path (string)
  2. Data: The content to write (string or Buffer)
  3. Callback: A function that runs when done, receiving an error if something went wrong

Writing Different Content Types

// Write a string
fs.writeFile('message.txt', 'Simple text content', (err) => {
  if (err) throw err;
  console.log('String written');
});

// Write a Buffer
const buffer = Buffer.from('Binary data');
fs.writeFile('data.bin', buffer, (err) => {
  if (err) throw err;
  console.log('Buffer written');
});

Important Behavior

If the file doesn't exist, fs.writeFile() creates it. If it does exist, the method completely replaces the file's content—it doesn't append. Your old data is gone unless you've backed it up elsewhere.

Key Takeaway: fs.writeFile() asynchronously creates or overwrites files with string or Buffer content, using a callback to handle success or errors without blocking your program's execution.