NodeJS

How to Perform Various File Operations in Node.js?

This blog describes How to Perform Various File Operations in Node.js.

The following code shows a basic Node.js application that performs various file operations like reading, writing, copying, and deleting files.

const fs = require('fs');
const path = require('path');

// Function to read a file
function readFile(filePath) {
    fs.readFile(filePath, 'utf8', (err, data) => {
        if (err) {
            console.error('Error reading file:', err);
            return;
        }
        console.log('File contents:', data);
    });
}

// Function to write to a file
function writeFile(filePath, content) {
    fs.writeFile(filePath, content, 'utf8', (err) => {
        if (err) {
            console.error('Error writing to file:', err);
            return;
        }
        console.log('File written successfully');
    });
}

// Function to copy a file
function copyFile(source, target) {
    fs.copyFile(source, target, (err) => {
        if (err) {
            console.error('Error copying file:', err);
            return;
        }
        console.log('File copied successfully');
    });
}

// Function to delete a file
function deleteFile(filePath) {
    fs.unlink(filePath, (err) => {
        if (err) {
            console.error('Error deleting file:', err);
            return;
        }
        console.log('File deleted successfully');
    });
}

// Usage examples
const sourceFile = path.join(__dirname, 'source.txt');
const targetFile = path.join(__dirname, 'target.txt');

readFile(sourceFile);
writeFile(targetFile, 'Hello, world!');
copyFile(sourceFile, targetFile);
deleteFile(targetFile);

source.txt

Source Text File
Source Text File

Output

File Operations: read, write, copy, and delete
File Operations: read, write, copy, and delete

Make sure to create a source.txt file in the same directory as this script to test the read, write, copy, and delete operations. This script uses the fs (File System) module, which is built into Node.js, to perform file operations asynchronously.


Further Reading

JUnit Tutorial

Spring Framework Practice Problems and Their Solutions

30 MCQs on JUnit

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

100+ MCQs On Java Architecture

Java Practice Exercise

programmingempire

Princites

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *