0
0
Node.jsframework~5 mins

Why file system access matters in Node.js

Choose your learning style9 modes available
Introduction

File system access lets your program read and save files on your computer. This is important to keep data, settings, or logs outside the program itself.

Saving user settings so they stay after the program closes
Reading data files to use inside your app
Writing logs to track what your program did
Loading templates or resources stored as files
Creating or deleting files as part of your app's work
Syntax
Node.js
import { promises as fs } from 'fs';

// Read a file
const data = await fs.readFile('path/to/file.txt', 'utf-8');

// Write to a file
await fs.writeFile('path/to/file.txt', 'Hello world');

Use the 'fs' module in Node.js to work with files.

Use 'await' with promises to handle file operations asynchronously.

Examples
This reads the file 'notes.txt' and prints its content.
Node.js
import { promises as fs } from 'fs';

// Read a text file
async function readFile() {
  const content = await fs.readFile('notes.txt', 'utf-8');
  console.log(content);
}

readFile();
This saves the text into 'message.txt'.
Node.js
import { promises as fs } from 'fs';

// Write a message to a file
async function writeFile() {
  await fs.writeFile('message.txt', 'Hello from Node.js!');
}

writeFile();
This removes the file named 'oldfile.txt' from your system.
Node.js
import { promises as fs } from 'fs';

// Delete a file
async function deleteFile() {
  await fs.unlink('oldfile.txt');
}

deleteFile();
Sample Program

This program writes a message to a file, reads it back, prints it, then deletes the file. It shows how to use file system access to save and retrieve data.

Node.js
import { promises as fs } from 'fs';

async function demoFileAccess() {
  const filename = 'example.txt';
  const message = 'This is a test file.';

  // Write message to file
  await fs.writeFile(filename, message);

  // Read the message back
  const readMessage = await fs.readFile(filename, 'utf-8');

  // Print the content
  console.log('File content:', readMessage);

  // Delete the file
  await fs.unlink(filename);
  console.log('File deleted.');
}

demoFileAccess();
OutputSuccess
Important Notes

Always handle errors in real apps when working with files to avoid crashes.

Use asynchronous methods to keep your app responsive.

File paths can be absolute or relative to your program's folder.

Summary

File system access lets your app save and load data outside the program.

Node.js provides easy-to-use methods to read, write, and delete files.

Using async file operations keeps your app fast and smooth.