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.

OS Module

Currently, your index.js imports the OS module.

import os from "os";

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

Path Module

Let's play around with the Path module.

import path from "path";

const pathObj = path.parse(import.meta.url);

console.log(pathObj);

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

{
  root: '',
  dir: 'file:///Users/alimadooei/Desktop/node-demo',
  base: 'index.js',
  ext: '.js',
  name: 'index'
}

FS Module

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

import fs from "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:

[ 'index.js', 'package.json' ]

There is an asynchronous version of this function:

import fs from "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!

import fs from "fs/promises";

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

_readdir("./");