Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

File system in nodeJS

Introduction
  1. The fs module enables interacting with the file system in a way modelled on standard POSIX functions
  2. To use the promise-based APIs
  3. To use the callback and sync APIs
  4. All file system operations have synchronous, callback, and promise-based forms
// Using ESM Module syntax:
import * as fs from 'fs/promises';
// Using ESM Module syntax:
import * as fs from 'fs';
Write to file
Example to write some content to file
import { writeFile } from 'fs/promises';

try {
    const data = new Uint8Array(Buffer.from('Hello Node.js'));
    writeFile('message.txt', data);
} catch (err) {
    console.error(err);
}
// Writes Hello Node.js to file message.txt