{ Core Node.js Modules. }

Objectives:

By the end of this chapter, you should be able to:

  • Compare and contrast how node finds built-in modules vs. custom modules
  • Import and use core modules like fs, path, and process

Built-in modules

So far we have seen how to create our own modules, but there are quite a few modules that come built into Node.js. We call these modules core modules and many of them are the foundation for more complex technologies and libraries that we will be using. You can see a full list of them here. Let's examine some of the built-in modules as we will be using a few of them later!

File System

The file system or fs module can be used to read files, write to files, and append files. It is extremely useful for working with text files, comma separated values (csv) files and many others. The fs module can also be used to create and modify files and folders.

Let's first create a file called data.txt and place some text inside of it. Then, create a file called read.js and place the following code in it:

var fs = require("fs");

fs.readFile('data.txt', function(err,data){
    console.log(data.toString());
})

When we run node read.js we will see the contents of that file. Notice that the second parameter passed to readFile is a callback function! We will discuss a little bit later why that is, but keep this example in the back of your mind.

Asynchronous environment

What do you notice about the code above? The readFile function accepted a filename and then a callback function! What we are seeing is that the entire Node.js environment is asynchronous. When one process begins running, it does not block the rest of our code from continuing to execute. While this makes Node.js very effective for certain tasks, it also makes it tricky to manage when first learning it. We will see how to manage our asynchronous code using callbacks and promises, but it's essential to remember that Node.js uses the event loop to handle processes asynchronously.

You can read more about this here and here.

Path

The path module is quite helpful for working with file paths, extending file paths, and determining types of paths.

var path = require("path");

// Normalize a path
console.log(path.normalize('/test/test1//2slashes/1slash/tab/..')); // /test/test1/2slashes/1slash

// Join multiple paths together
console.log(path.join('/first', 'second', 'something', 'then', '..')); // /first/second/something

// Resolve a path (find the absolute path)
console.log(path.resolve('first.js')); 

// Find the extention of a filename
console.log(path.extname('main.js')); // .js

Process

The process module can be used for quite a few things, including accepting command line arguments (argv) and listening for specific events (on). You can listen for a variety of events, including exiting or even the next tick of the event loop. We can also use the process object to access environment variables using process.env Instead of importing this module, process is a reserved keyword in Node that we can use! Let's make a file called args.js and inside let's place the following:

console.log(process.argv);

Now let's run node args.js 1 2 3 and we should see an array with values! The first value refers to the command which we are using to run node, the second is the absolute path to our file and the remaining ones are our arguments. How can we now print out only a list of 1, 2 and 3?

HTTP

The HTTP (and HTTPS) module allows you to create a server and issue HTTP requests and responses. You can use this module on its own to create a server, but using it involves a fair amount of code and complexity. This module is one of the essential parts of express.js, which is a framework that abstracts some of the more challenging and tedious parts of routing.

var http = require('http');
// notice below, the first parameter to createServer is a callback function!
var server = http.createServer(function(req, res, next) {
  // sending some header info in my response
  res.writeHead(200, {'Content-type' : 'text/html'});
  // send some data to the client
  res.write("<h1>Hello World!</h1>");
  // end the response
  res.end();
});
// notice below, another callback function!
server.listen(3000, function(){
  console.log("Go to localhost:3000");
});

To practice with core node modules and learn more, you can walk through learnyounode, which is a wonderful resource for learning node.js fundamentals.

You can also see a small app using the fs module here

When you're ready, move on to Introduction to NPM

Continue