Important Node.js Modules You Should Know
Tags: webdev, beginners, programming, javascript
Published: 2022-12-21 14:44:59

Here are important node.js inbuilt modules that you can't avoid using whether as a beginner or experienced node.js developer. 


## Filesystem

Node.js filesystem allows you to work with files on your computer. There are several ways you can handle these files. You could create, read, write, update, delete, and rename a file. To work with the filesystem, the first to do is require it:

`const fs = require ("fs");`

The filesystem can be synchronous or asynchronous. To work with an asynchronous filesystem, require `fs/promises`


### Create file

There is more than one way to do this:

`fs.open()
fs.writeFile()
fs.appendFile()`

Any of these methods will create a new file if it doesn't already exist and they take in the name of the file, the content, and a callback function.

```

fs.writeFile("data.txt", "Hello World", (err)=>{
if(err) throw err;
})


```

`fs.open()` is quite versatile as it takes a "flag" argument that indicates what you want to do with the file. **"w"** flag means the file is open for writing, and **"r"** means you want to read from the file. It works for creating a file because if the file indicated does not exist, it's going to be created.


### Read a file

The method `fs.readFile()` or `fs.read()` is used to read from a file. This method takes the name of the file and a callback function.

```

const fs = require('fs');

function readFile(){
  await fs.readFile("data.txt", "utf-8" (err, data)=>{
    if (err) throw err;
     console.log(data);
})
}
 
```


### Delete

To delete a file use the fs.unlink() method.
`fs.unlink("data.txt")`

### Rename

Use `fs.rename()`. It takes in the name of the file then the new name followed by a callback function.

```
fs.rename("data.txt", "newData.txt", (err)=>{
  if (err) throw err;
  console.log('rename successful!')
})
```


## Path

To work with files on your system, it is important to be able to know the path correctly. There are two types of file paths. 

**Absolute path
Relative path**

An absolute path specifies the location of a file or directory from the root or (/) directory.

`C: \desktop\tuts\data.txt`

Relative path defines the path as related to the present working directory.

`data.txt`

Node.js has an inbuilt path module that makes it easier to work with file paths. To use it, the first thing is to require it

`const path = require("path")`

This gives you access to different path methods and the most common you will mostly use/come across are` path.resolve` and `path.join`

The `path.resolve()` method resolves a sequence of paths or path segments into an absolute path. The given path fragments are processed from right to left. If no path segments are passed, path.resolve() will return the absolute path of the current working directory.


### path.join

The `path.join()` method joins all given path segments together and then normalizes the resulting path. 


### path.dirname

The `path.dirname()`method returns the directory name of a path, this is especially useful for knowing the directory where a file is saved. 


### path.extname()

This method returns the file extension from the path. It starts from the last period character (.) to the end of the given string/path. If there is no period, an empty string is returned.


```
path.extname('index.html');
// Returns: '.html'
```


## Stream

Stream is another inbuilt module in Node.js that is used for working with streaming data. It is great for saving time and memory. When the data to be written or read in a file is huge, it is better to use streams. An example is uploading/downloading/streaming videos. Streams are readable and writable. You can have access to the stream module by requiring it.

`const stream = require('node:stream');
`
The methods `fs.createReadStream()`and `fs.createWriteStream()` are used to stream data to be written or read.

```
http.createServer(function(req, res)=>{
 const stream = fs.createReadStream("data.json");
 stream.pipe(res); //streams the data inside the json file
}).listen(5000)
```


## Events

As a JavaScript developer, you should know about events triggering and have worked with this concept more than you can count. Events refer to every action that occurs on a computer. Objects in Node.js can fire events, like the readStream object fires events when opening and closing a file. 

You can work with events in Node.js too as it has a built-in events module. You first require it to start creating, firing, or listening for your events. Also, events are instances of EventEmitter object, so you must create an EventEmitter object too to have access to its properties and methods.


```
const events = require('events');
const eventEmitter = new events.EventEmitter();
```

The **EventEmitter** object allows you to assign event handlers to your own events. We use the emit() method to fire an event. Here is an example of how to work with events:


```
let event = new events.eventEmitter();

event.on('event-name', function (data) {
  console.log('You just did something:', data);
});

event.emit('event-name');

```
The above code initialized a new instance of the eventEmitter object. The "on" method is used to create an event while the "emit" method fires the event.



## HTTP

Hyper Text Transfer Protocol (HTTP) is used to communicate between the web server and browser among other things. It is used for transmitting hypermedia documents like HTML. Node.js has an inbuilt http module that is meant to tap into the power of HTTP. Node.js HTTP module is essentially used to create servers. We require it like this:    

`const http = require('http');
`
To create an HTTP server in node.js, we use the createServer() method. The syntax looks like this:


```
const http = require('http');

http.createServer((req, res)=>{
  res.end('Hello World'); 
}).listen(5000);

```
The `createServer()` method takes a function that handles the request and response between the server and the user. The listen() method indicates the port where the server can be accessed (5000).