Working with files

Working with files #

Working with files is a common task in Node.js, allowing developers to read, write, and manipulate file data. Here’s a basic overview of file operations in Node.js:

File System Module (fs): #

Node.js provides the fs module for file-related operations. To use it, require the module at the beginning of your script:

const fs = require('fs');

Reading Files: #

Use the fs.readFile method to read the contents of a file asynchronously:

fs.readFile('example.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    console.log('File content:', data);
});

For synchronous reading, use fs.readFileSync:

try {
    const data = fs.readFileSync('example.txt', 'utf8');
    console.log('File content:', data);
} catch (err) {
    console.error('Error reading file:', err);
}

Writing to Files: #

To write to a file, use fs.writeFile asynchronously:

const content = 'Hello, Node.js!';

fs.writeFile('output.txt', content, 'utf8', (err) => {
    if (err) {
        console.error('Error writing to file:', err);
        return;
    }
    console.log('Write operation complete.');
});

For synchronous writing, use fs.writeFileSync:

const content = 'Hello, Node.js!';

try {
    fs.writeFileSync('output.txt', content, 'utf8');
    console.log('Write operation complete.');
} catch (err) {
    console.error('Error writing to file:', err);
}

Appending to Files: #

Use fs.appendFile to add content to an existing file asynchronously:

const additionalContent = 'Appending more data.';

fs.appendFile('output.txt', additionalContent, 'utf8', (err) => {
    if (err) {
        console.error('Error appending to file:', err);
        return;
    }
    console.log('Append operation complete.');
});

For synchronous appending, use fs.appendFileSync:

const additionalContent = 'Appending more data.';

try {
    fs.appendFileSync('output.txt', additionalContent, 'utf8');
    console.log('Append operation complete.');
} catch (err) {
    console.error('Error appending to file:', err);
}

Checking File Existence: #

To check if a file exists, use fs.existsSync (synchronous) or fs.access (asynchronous):

const filePath = 'example.txt';

// Synchronous
if (fs.existsSync(filePath)) {
    console.log('File exists.');
} else {
    console.log('File does not exist.');
}

// Asynchronous
fs.access(filePath, fs.constants.F_OK, (err) => {
    if (err) {
        console.log('File does not exist.');
    } else {
        console.log('File exists.');
    }
});

Deleting Files: #

Use fs.unlink to delete a file asynchronously:

fs.unlink('fileToDelete.txt', (err) => {
    if (err) {
        console.error('Error deleting file:', err);
        return;
    }
    console.log('File deleted successfully.');
});

For synchronous deletion, use fs.unlinkSync:

try {
    fs.unlinkSync('fileToDelete.txt');
    console.log('File deleted successfully.');
} catch (err) {
    console.error('Error deleting file:', err);
}

Working with Directories: #

The fs module also provides methods for working with directories, such as fs.mkdir, fs.readdir, and fs.rmdir.

Streams for Large Files: #

For large files, consider using streams (fs.createReadStream and fs.createWriteStream) to read and write data in chunks, minimizing memory usage.

Path Module: #

The path module assists in working with file and directory paths in a platform-independent manner.

const path = require('path');
const fullPath = path.join(__dirname, 'files', 'example.txt');
Working with files in Node.js is fundamental for many applications. Understanding the synchronous and asynchronous file operations, error handling, and the use of streams for efficiency contributes to building robust and performant file-related functionality.

Happy coding!
Published on