Loading...

NodeJS - Built-in modules and globals

Lesson Plan

In this lesson we will go over some of the popular built ins in node js. Built-in modules are modules that are compiled in the binary of NodeJs and can be required without the need to install additional modules. We will also cover some globals that are popular to use.

Globals

To start the lesson lets first go over some globals we have in node that we can use.

Timers

timers can be used to scheduale work to be done in the future. setTimeout will set a function to run once after x miliseconds. setInterval will set a function to run repetitvly after every x miliseconds. both of those functions will return an id number of the timeout or interval which can be used to cancel them. clearTimeout given the id of the timer it will cancel it. clearInterval given the id of the interval it will cancel it. Lets create a timer that runs every second and prints to the console, and after 2 seconds lets cancel that timer.

        
            let counter = 0;
            const intervalId = setInterval(function() {
                console.log(counter);
                counter++;
                if (counter > 2) {
                    clearInterval(intervalId);
                }
            }, 1000);
        
    
Process

Provide information and control about the current node process. process.cwd returns the current working directory of the process, from what directory did we run node. process.env provide user environment variables and a good way to pass to the node process sensitive information. Lets try and set environment variable and pass it to the node process. Create a file called env-tutorial.js with the following code:

        
            console.log(process.env.FOO);
        
    

Now run this file with a FOO environment variable like so:

        
            > FOO=bar node env-tutorial.js
        
    
Errors

There is a convention of reporting errors in Node. All errors inherit from a base Error class, the Error class have a code which is a string code of the error, a message describing the error, and a stack trace of the error origins. There are also different classes extending the Error class like: SyntaxError. You can also extend the Error class yourself. you can throw error and catch errors in a try and catch block.

Built-in Modules

NodeJS has a lot of built-in modules, and in this lesson we will cover the popular ones. Since there is a lot of those modules, and in each of the module there are a lot of methods, the idea of the lesson is: - understand what the module is in charge of - know how to use a method or two - know where to find the api for the module to learn additional methods in the future. So Lets start...

fs - File System

The fs module is in charge of dealing with the file system. Using this module we read files, check if file exists, check directory and files in directory, delete files and more. The documentation for this module is located here Most of the methods in this module consist of sync methods and async methods, for example you can read a file in a sync way which means the process will block until the file is read, and you can read the same file in an async way without blocking the process. It's recommended to always use the async methods for better performance. Lets create a simple script that can read a file. First create a folder for this lesson, and create a text file in that folder:

        
            > mkdir node-builtins
            > cd node-builtins
            > echo "this text i want to read from file" > stam.txt
        
    

we will now write a small script that reads the stam.txt that we created. create a file called fs-tutorial.js with the following code:

        
            const fs = require('fs');
            fs.readFile('stam.txt', function(err, result) {
                console.log(result.toString());
            });
        
    

Notice that the method fs.readFile is an async non blocking method, and our callback will be called after the reading of file is done. The first argument is the file we want to read, which will usually be a string of relative or absolute path to the file. Relative path is relative to the working directory from which we started the process (the same directory from which we executed node). The second argument is a callback to be called after the reading of the file is done. The callback is a typical node style error first callback, you will see this kind of callbacks repeats in node's non blocking api's callbacks. The first argument is the err which will be null if there is non, the second is the result of the API. The same method exists with a blocking of the process and done in a synchronously way. The sync methods in this module have the same name as the async but with a suffix of Sync. So the following code will produce the same result as the above only with poor performance:

        
            const fs = require('fs');
            const text = fs.readFileSync('stam.txt');
            console.log(text.toString());
        
    
Path

Provide utilities for working with file and directory paths. Lets try and use this module to get the absolute path of the file stam.txt to do this we will append __dirname which we contains the absolute directory path of the module that is currently run (more about it in this lesson), with the filename.

        
            const path = require('path');
            console.log(path.resolve(__dirname, 'stam.txt'));
        
    
EventEmitter

Javascript relies heavily on async callbacks and events. The event emitter is used to shout that something happened and the listeners to that shout will run synchronously. You shout an event by calling the emit method with the name of the event and additional arguments to pass to the listeners. You attach listeners with the on method or if want to listen only once you can use the once method. In the listener function this is set as the instance of the event emitter. What would happen if we use lambda function instead? This will be set as what wrapps the lambda function. Lets create a timer event which is invoked after 2 seconds:

        
            const EventEmitter = require('events')
            const timerEvent = new EventEmitter();

            timerEvent.on('timer', function() {
                console.log('i listened to the timer event');
            });

            setTimeout(function() {
                timerEvent.emit('timer');
            }, 2000);
        
    

A lot of the api of the modules in node will return an event emitter which you can subscribe to events. There will usually be an error event to listen to if the event emitter throws and error. If we registered a listener to this event it will catch the errors otherwise the error will exit the process.

http

This module provide us ways to send requests and to listen to requests on a port. First lets try to use this module to listen on port 3001 for requests and send response for those request with an hello world message.

        
            const http = require('http')
            const server = http.createServer((req, res) => {
                res.write('hello world');
                res.end();
            });

            server.listen(3001)
        
    

the method createServer gets a method that will be called when a request is sent. In this method we can use the res which is a response object to send the data back. We are then listening on port 3001 for requests so you can open your browser and browser to localhost on port 3001 and you should see an hello world message. Now lets try and send a request to a remote api. For Nerdeez courses we have a todo rest server located at the url: https://nztodo.herokuapp.com this server expose a rest api to grab todo tasks from a database table at the path: /api/task?format=json lets send a request to grab all the todo task items from this server. We can do this with the https module with the following code:

        
            const https = require('https');

            https.get('https://nztodo.herokuapp.com/api/task/?format=json', res => {
                res.on('data', d => console.log(d.toString()));
            });
        
    

Since we are querying a rest server with an ssl we better use the https module. We use the get method with a string of the url we want to grab. This will call our callback with the response with the data from the server as stream we can connect to with the on data event. So the response we are getting is an instance of an EventEmitter which we can subscribe listeners to the data event to get the response body. We are printing the result to the console.

Summary

We covered here the most popular modules and globals when using node. Of course there are more of those but these are most used. In our next lesson we will cover async non blocking methods in node js and how to deal with them properly.