0
0
Node.jsframework~5 mins

Writing files in Node.js

Choose your learning style9 modes available
Introduction

Writing files lets your program save information on the computer. This helps keep data even after the program stops.

Saving user settings or preferences
Logging events or errors for later review
Creating reports or exporting data
Storing temporary data between program runs
Syntax
Node.js
import { writeFile } from 'node:fs/promises';

await writeFile('filename.txt', 'Your content here');
Use the 'fs/promises' module for easy async file writing with await.
The first argument is the file path, the second is the content to write.
Examples
Writes 'Hello, world!' to a file named hello.txt.
Node.js
import { writeFile } from 'node:fs/promises';

await writeFile('hello.txt', 'Hello, world!');
Saves a JSON string to data.json file.
Node.js
import { writeFile } from 'node:fs/promises';

await writeFile('data.json', JSON.stringify({ name: 'Alice', age: 30 }));
Writes multiple lines to notes.txt using newline characters.
Node.js
import { writeFile } from 'node:fs/promises';

await writeFile('notes.txt', 'Line 1\nLine 2\nLine 3');
Sample Program

This program writes a simple message to 'message.txt' and then prints a confirmation.

Node.js
import { writeFile } from 'node:fs/promises';

async function saveMessage() {
  const message = 'This is a saved message.';
  await writeFile('message.txt', message);
  console.log('File saved successfully!');
}

saveMessage();
OutputSuccess
Important Notes

Always handle errors in real programs to catch issues like permission problems.

Writing files is asynchronous; use async/await or promises to wait for completion.

File paths can be relative or absolute. Relative paths are from where you run the program.

Summary

Writing files saves data permanently on your computer.

Use the 'fs/promises' module with async/await for simple, clean code.

Remember to handle errors and choose correct file paths.