📂File Management with JavaScript in Node.js

📂File Management with JavaScript in Node.js

·

4 min read

Node.js is an engine that allows us to run JavaScript outside the browser. Many applications today are powered by Node.js, offering numerous advantages and a few drawbacks. However, my intention today is not to introduce Node.js or JavaScript. Today, I want to showcase how we can manage files on our computer using JavaScript.

One of the built-in modules in Node.js is the file system module.

This module provides us with all CRUD functions (Create, Read, Update, and Delete):

  • Creating files

  • Reading files

  • Renaming files

  • Updating files

  • Deleting files

File management like this is useful when we want to write something to a file, such as logging. Additionally, we'll likely use this module when our application users are changing their profile pictures.

This module allows us to manage files both asynchronously and synchronously.

File System Module

Before using the library, we need to import it, just like importing any other libraries in JavaScript. Importing is done using the require function.

let fileSystem = require('fs');

Deleting Files

To delete files, we use the unlink or unlinkSync function.

unlink is used for asynchronous file deletion, allowing us to use callbacks, which unlinkSync does not.

const fs = require('fs');

fs.unlink('./fileForDelete.txt', (error) => {
     if (error) throw error;
     console.log('Successfully deleted the file.');
});

The function takes the path to the file to be deleted as the first parameter and a function as the second parameter, which notifies of any errors or provides a success message.

Creating Files

For creating files, we use the writeFile or writeFileSync function.

writeFile

The writeFile function allows asynchronous file creation.

const fs = require('fs');

const content = 'Content of the file to be created.';

fs.writeFile('./newFile.txt', content, (error) => {
     if (error) throw error;
     console.log('File successfully created.');
});

The writeFile function takes the path to the file (first parameter), the content of the file (second parameter), and a function that handles any errors or reports success (third parameter).

writeFileSync

The writeFileSync function allows synchronous file creation.

const fs = require('fs');

const content = 'Content of synchronously created file.';

fs.writeFileSync('./newSyncFile.txt', content);

console.log('Synchronous file successfully created.');

The writeFileSync function takes the path to the file (first parameter) and the file's content (second parameter).

Reading Files

For reading files, we use the readFile or readFileSync function.

readFile

The readFile function allows asynchronous file reading.

const fs = require('fs');

fs.readFile('./existingFile.txt', 'utf8', (error, data) => {
     if (error) throw error;
     console.log('File content:', data);
});

The readFile the function takes the path to the file (first parameter), an option for decoding the file content (in this case, 'utf8'), and a function that handles any errors or returns the read content (third parameter).

readFileSync

The readFileSync function allows synchronous file reading.

const fs = require('fs');

const data = fs.readFileSync('./existingSyncFile.txt', 'utf8');
console.log('Synchronous file content:', data);

The readFileSync function takes the path to the file (first parameter) and an option for decoding the file content (in this case, 'utf8').

Renaming Files

For renaming files, we use the rename or renameSync function.

rename

The rename function allows asynchronous file renaming.

const fs = require('fs');

fs.rename('./oldName.txt', './newName.txt', (error) => {
     if (error) throw error;
     console.log('File successfully renamed.');
});

The rename function takes the current name of the file (first parameter), the new name of the file (second parameter), and a function that handles any errors or reports success (third parameter).

renameSync

The renameSync function allows synchronous file renaming.

const fs = require('fs');

fs.renameSync('./oldSyncName.txt', './newSyncName.txt');

console.log('Synchronous file successfully renamed.');

The renameSync function takes the current name of the file (first parameter) and the file's new name (second parameter).

Updating Files

For updating files, we can use the appendFile or appendFileSync function.

appendFile

The appendFile function allows asynchronous appending to an existing file.

const fs = require('fs');

const additionalContent = '\\nAdditional content for updating the file.';

fs.appendFile('./existingFile.txt', additionalContent, (error) => {
     if (error) throw error;
     console.log('File successfully updated.');
});

The appendFile function takes the path to the file (first parameter), additional content (second parameter), and a function that handles any errors or reports success (third parameter).

appendFileSync

The appendFileSync function allows synchronous appending to an existing file.

const fs = require('fs');

const additionalSyncContent = '\\nSynchronous additional content for updating the file.';

fs.appendFileSync('./existingSyncFile.txt', additionalSyncContent);

console.log('Synchronous file successfully updated.');

The appendFileSync function takes the path to the file (first parameter) and additional content (second parameter).

These are the basic operations provided by the file system module in Node.js, and they are crucial for managing files using JavaScript. With these functions, we can efficiently create, read, update, and delete files on our computer.

Conclusion

In summary, Node.js's file system module empowers developers to efficiently manage files using JavaScript. The module offers CRUD functions, allowing for flexible file operations in both asynchronous and synchronous modes.

Whether handling logs, user-uploaded files, or routine file management, Node.js provides a robust solution. Key functions like writeFile, readFile, rename, unlink, and appendFile, along with their synchronous counterparts, enable developers to tailor file operations to their application's requirements.

Did you find this article valuable?

Support Patrick by becoming a sponsor. Any amount is appreciated!