How should I read file TypeScript using Node.js?

How should I read file TypeScript using Node.js? I’m unsure if file operations would be sandboxed in Node.js, but I believe there should be a way to access the file system. How can I perform read file operations such as reading from and writing to a text file in TypeScript?

Hi,

The fs (File System) module provides methods for reading and writing files synchronously. This method blocks execution until the operation completes.

import * as fs from 'fs';

// Reading a file
const data = fs.readFileSync('path/to/your/file.txt', 'utf8');
console.log(data);

// Writing to a file
fs.writeFileSync('path/to/your/file.txt', 'Hello, World!', 'utf8');

For non-blocking file operations, use the asynchronous methods provided by the fs module. This is more efficient for I/O operations.

import * as fs from 'fs';

// Reading a file
fs.readFile('path/to/your/file.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
});

// Writing to a file
fs.writeFile('path/to/your/file.txt', 'Hello, World!', 'utf8', (err) => {
    if (err) throw err;
    console.log('File has been saved!');
});

The fs/promises API provides promise-based methods for file operations, allowing you to use async/await for cleaner code.

import { promises as fs } from 'fs';

async function readFile() {
    try {
        const data = await fs.readFile('path/to/your/file.txt', 'utf8');
        console.log(data);
    } catch (err) {
        console.error('Error reading file:', err);
    }
}

async function writeFile() {
    try {
        await fs.writeFile('path/to/your/file.txt', 'Hello, World!', 'utf8');
        console.log('File has been saved!');
    } catch (err) {
        console.error('Error writing file:', err);
    }
}

readFile();
writeFile();