Working with Native Node Modules πŸ”‘

Node.js comes bundled with a set of core modules that provide essential functionalities for building applications. In this documentation, we'll explore the fs (File System) module, which allows us to interact with the file system on the server or local machine.

File System (fs) Module

The fs module provides an API for interacting with the file system, enabling reading from, writing to, and managing files. It's a crucial module for building server-side applications that handle file operations.

Writing to a File

To write data to a file, we can use the fs.writeFile() method. Here's an example:

const fs = require('fs');

fs.writeFile('message.txt', 'Hello from Node.js!', (err) => {

  if (err) throw err;

  console.log('File has been saved!');

});

1. Import the fs module using require('fs').

2. Call fs.writeFile() with three arguments:

- The file path (`'message.txt'`)

- The data to write (`'Hello from Node.js!'`)

- A callback function to handle errors or success

This code will create a new file called message.txt (or overwrite it if it already exists) in the same directory as your script, and write the provided string to it.

Reading from a File

To read data from an existing file, we can use the fs.readFile() method:

const fs = require('fs');

fs.readFile('message.txt', 'utf8', (err, data) => {

  if (err) throw err;

  console.log(data);

});

1. Import the fs module using require('fs').

2. Call fs.readFile() with three arguments:

- The file path (`'message.txt'`)

- The encoding (`'utf8'` for text files)

- A callback function to handle errors or the file data

This code will read the contents of the message.txt file and log it to the console.

πŸ”‘ By leveraging the fs module, you can easily read from and write to files in your Node.js applications. This is a crucial functionality for server-side operations like logging, data storage, and more.

Challenge: Modifying File Contents

1. Open the message.txt file and change its contents to "Hello from [Your Name]!".

2. Modify the fs.readFile() code to read the updated contents of message.txt and log them to the console.

Give it a try, and feel free to explore the fs module documentation for more advanced file operations!