Node Modules

Node comes with a bunch of useful modules. You will find information about its modules on Node's online documentation. We will look at a few of these.

Path Module

Let's play around with the Path module first.

// index.js file
const path = require("path");

const pathObj = path.parse(__filename);

console.log(pathObj);

Notice the argument to require is not a file path. It simply is the name of the module. This is the pattern we use to load Node's built-in modules.

Run index.js, and you will get an output similar to this one:

{
  root: '/',
  dir: '/Users/alimadooei/Desktop/CS280/01-FA-20/staging/code/app',
  base: 'index.js',
  ext: '.js',
  name: 'index'
}

OS Module

Let's experiment with the OS module.

// index.js file
const os = require("os");

console.log(`Total memory ${os.totalmem()}`);
console.log(`Free memory ${os.freemem()}`);

Here is the output when I run the index.js file on my computer:

Total memory 17179869184
Free memory 544534528

FS Module

Let's experiment with the File system (FS) module.

// index.js file
const fs = require("fs");

const files = fs.readdirSync("./");

console.log(files);

The readdirSync will synchronously read the files stored in the given directory (the path to the directory is given as an argument to readdirSync function).

On my computer, running index.js results in:

[ 'account.js', 'index.js' ]

There is an asynchronous version of this function:

// index.js file
const fs = require("fs");

fs.readdir("./", (err, files) => {
  console.log(files);
});

Notice we have used the callback pattern to deal with the async operation. The readdir function was written before JavaScript had a Promise object. The function does not return a Promise, so we cannot use the Promise pattern (nor async/await) here.

If you want to use the async/await or promise syntax, you must write your own. However, some built-in modules have a promise-based alternative that has recently been added!

const fs = require("fs/promises");

async function _readdir(path) {
  try {
    const files = await fs.readdir(path);
    console.log(files);
  } catch (err) {
    console.log(err);
  }
}

_readdir("./");