Learn nodejs (P3): Read and write files using FileSystem Module and how to create a new module yourself

Tram Ho

1. Modules in nodejs

As from the previous examples we used the command:

const http = require('http');

The http here is a built-in module of nodejs.

We call http via require and assign it to a variable, which allows us to create an instance of this module. This way, we can use all the functions built into the http module.

2. Use the FileSystem Module to read and write files

To use the FileSystem module we use

2.1 Synchronous processing

First we use read and write files synchronously (synchronous) with readFileSync and writeFileSync .

Note : The second parameter is the encoding type, when passing this parameter, the returned data will be String , otherwise, the readFileSync function will return the buffer as follows

2.2 Asynchronous processing

Another way to read files is to read asynchronous files using the readFile function. So how are these 2 ways of reading this file different?

Here we need a callback function, which simply reports an error if there is an error and otherwise prints the data from the file.

Test the code above and here’s the result:

We can see that here, when the large data file and the readFile function cannot be processed immediately, the server will continue to run the code below while the readFile function continues to perform its task. This will bring many performance benefits when the actual problem requires processing multiple requests at once.

3. Create your own custom modules

Nodejs allows us to create our own modules.

For example, we want to create a module that can say hello in many languages, for example.

First, create the file hello.js

We can use the exports keyword to be able to use these functions in the main file (app.js).

In the app.js file we can call this module the same way we use it to call http .

Note : There is a more ‘beautiful’ way that we can use to declare functions in a module.

Reference source:



Share the news now

Source : Viblo