Categories
Express JavaScript Nodejs

To store sessions in our Express apps, we can use the cookie-session middleware.

It’s a cookie-based session middleware that stores user sessions on the client within a cookie.

In this article, we’ll look at how to store sessions within an Express app with the cookie-session middleware.

How Cookie-Session Stores Sessions?

cookie-session doesn’t require any database or other server-side resources to store sessions. The session data can’t exceed the browser’s max cookie side.

It can also simplify certain load-balanced scenarios. It can also store a light session and include an identifier to look up a database-backed secondary store to reduce database lookups.

Adding the Library

We can install cookie-session by running:

npm i cookie-session

Then we can use it as follows:

const cookieSession = require('cookie-session')  
const express = require('express')  
  
const app = express()  
  
app.use(cookieSession({  
  name: 'session',  
  keys: 'secret',  
  maxAge: 24 * 60 * 60 * 1000  
}))

Options

The cookie-session middleware lets us pass in an options object with various properties to set the value.

This middleware will automatically add a Set-Cookie header to the response if the contents of the req.session were altered.

The Set-Cookie header won’t be in the response unless there are contents in the session, so we should add something to req.session as soon as we have identifying information to store the session.

The following options are available:

name

Name of the cookie to be set and defaults to session .

keys

The list of keys to sign and verify cookie values, or a Keygrip instance. Set cookies are always signed with keys[0] , and other keys are valid for verification.

This allows for key rotation. It can be used to change signature parameters like the algorithm of the signature.

secret

The string will be used as a single key if keys isn’t provided.

Cookie Options

The cookie object within the options have the following properties:

  • maxAge — a number of milliseconds from Date.now() for expiry
  • expires — a Date object indicating the cookie’s expiration date
  • path — a string indicating the path of the cookie, which defaults to /
  • domain — a sting indication the domain of the cookie
  • sameSite — boolean or string indicating whether the cookie is a ‘same site’ cookie. The default value is false , 'strict' , 'lax' or true are other possible values
  • secure — boolean indicating whether the cookie is only sent over HTTPS. If this is true and communication isn’t through TLS, then the cookie may not be set correctly
  • httpOnly — boolean indicating whether the cookie is sent over HTTP(S) and not available to client JavaScript
  • signed — boolean indicating whether the cookie is signed. Default value is true . If it’s true , then the cookie is appended with a .sig suffix.
  • overwrite — boolean indicating whether to overwrite previously set cookies of the same name

req.session

req.session holds the session for the given request.

.isChanged

A method that returns trie is the session has been changed during the request.

.isNew

A method that returns true if the session is new.

.isPopulated

A method that returns true is the session has been populated with data.

req.sessionOptions

We can set the sessionOptions object to change cookie settings.

Destroying a Session

We can set req.session to null to destroy a session.

Example

We can track the number of views a user made as follows:

const express = require('express');  
const bodyParser = require('body-parser');  
const cookieSession = require('cookie-session');  
const app = express();  
app.set('trust proxy', 1);  
app.use(cookieSession({  
  name: 'session',  
  keys: ['key1', 'key2']  
}))
app.get('/', (req, res, next) => {  
  req.session.numViews = (req.session.numViews || 0) + 1  
  res.end(`${req.session.numViews} views`);  
})
app.listen(3000);

In the code above, we just set req.session with the properties that we want to add and set the values the way we want.

The numViews property is added to track the number of views and increments as more request to the / is made.

Setting Max Age

We can set the maxAge as follows:

const express = require('express');  
const bodyParser = require('body-parser');  
const cookieSession = require('cookie-session');  
const app = express();  
app.set('trust proxy', 1);  
app.use(cookieSession({  
  name: 'session',  
  keys: ['key1', 'key2'],  
  maxAge: 1000,  
}))
app.use((req, res, next) => {  
  req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge  
  next()  
})
app.get('/', (req, res, next) => {  
  req.session.numViews = (req.session.numViews || 0) + 1  
  res.end(`${req.session.numViews} views`);  
})
app.listen(3000);

We set maxAge to 1000 milliseconds above, then we’ll see that the values reset to 1 as the session expires.

In both cases, the Set-Cookie response header will be set as the session is set for the client.

We have multiple keys with the first one for encryption and the second one for verification.

Keygrip Integration

We can use keygrip as follows for encrypting our sessions:

const express = require('express');  
const bodyParser = require('body-parser');  
const cookieSession = require('cookie-session');  
const Keygrip = require('keygrip');  
const app = express();  
app.set('trust proxy', 1);  
app.use(cookieSession({  
  name: 'session',  
  keys: new Keygrip(['key1', 'key2'], 'SHA384'),  
  maxAge: 60 * 60 * 1000,  
}))
app.use((req, res, next) => {  
  req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge  
  next()  
})
app.get('/', (req, res, next) => {  
  req.session.numViews = (req.session.numViews || 0) + 1  
  res.end(`${req.session.numViews} views`);  
})
app.listen(3000);

In the code above, we set the encryption algorithm to SHA384 for secure encryption.

Conclusion

The cookie-session lets us store sessions securely. We can use it to store identifying information about a user securely by encrypting the content with keys.

Then we can get and set the data via req.session .

Various options are also available for sessions. We can set maxAge to set when the session expires.

We can use domain , path , sameSite , secure , and httpOnly to control what kind of domain and path to set in our cookies, and also set what sites the cookies will be set for.

cookie-session also works with Keygrip for encryption.

Categories
JavaScript

Some Useful Array Lodash Functions

Lodash is a utility library that has lots of methods for manipulating objects. It has stuff that we use all the time and also things that we don’t use frequently or don’t think of using.

In this article, we’ll look at some array methods from Lodash, including the chunk , compact, concat , difference , differenceBy , and differenceWith methods.

chunk

The chunk method lets us separate array entries into arrays with the given size and returns it. If the entries can’t be split evenly, then the final chunk will be the remaining elements.

It’s 2 arguments, which is the array to split and the chunk size of each entry of the split array.

For example, we can use it as follows:

import * as _ from "lodash";  
const array = [1, 2, 3, 4, 5, 6, 7];  
const result = _.chunk(array, 2);

Then we get:

[  
  [  
    1,  
    2  
  ],  
  [  
    3,  
    4  
  ],  
  [  
    5,  
    6  
  ],  
  [  
    7  
  ]  
]

assgined to result .

compact

The compact method creates an array with all the falsy values removed and returns it. Values false, null, 0, "", undefined, and NaN are falsy.

It takes one argument, which is the array to have those values removed.

For example, we can use it as follows:

import * as _ from "lodash";  
const array = [0, 1, 2, 3, null, false, undefined];  
const result = _.compact(array);

Then we get:

[  
  1,  
  2,  
  3  
]

assigned to result .

concat

The concat method creates a new array with the additional values added and returns it. It takes 2 or more arguments. The first is the array to add values to, and the rest are values that we want to add to the array.

We can use it as follows:

import * as _ from "lodash";  
const array = [1, 2, 3];  
const result = _.concat(array, 2, [3], [[4]]);

Then we get:

[  
  1,  
  2,  
  3,  
  2,  
  3,  
  [  
    4  
  ]  
]

assigned to result .

difference

difference remove the values that are given in the values array from the copy of the original array and returns the new array without the specified values.

SameValueZero comparison is used, which is the same as the === operator, except that NaN is the same as itself, and -0 and +0 are considered the same.

It takes 2 argument, which is the array to remove items from as the first argument, and the array with the values to remove from the array in the first argument as the second argument

For example, we can use it by writing:

import * as _ from "lodash";  
const array = [1, 2, 3];  
const result = _.concat(array, 2, [3], [[4]]);

Then we get:

[  
  1  
]

assigned to result .

differenceBy

We can use the differenceBy method to remove elements from an array and returns the new array with the items removed.

It takes 3 arguments, which is the array to remove items from. The second arguments have the values to exclude from the first array. The last argument is a function, which we can use to compare them items or a string with the property name for the value to compare.

For example, we can use it as follows:

import * as _ from "lodash";  
const result = _.differenceBy(  
  [{ name: "Joe" }, { name: "Jane" }],  
  [{ name: "Joe" }],  
  "name"  
);

Then we get back:

\[  
  {  
    "name": "Jane"  
  }  
]

which is assigned to result .

We can also pass in a comparator function instead of the string key for the property value that we want to check as the third argument:

import * as _ from "lodash";  
const fn = a => a.id.toString();  
const result = _.differenceBy([{ id: 1 }, { id: 2 }], [{ id: 1 }], fn);

The fn function has the a parameter which has the object that’s being looped through in the first array, so we can manipulate it the way we like to map it to new values.

Then we get back:

[  
  {  
    "id": 2  
  }  
]

and assigned to result .

differenceWith

Like differenceBy , differenceWith does the same thing but it only takes a comparator function as the third argument instead of both comparator or a string that has the key name that we want to compare.

The comparator has 2 parameters, which are the elements from the first and second array in the arguments respectively.

It also returns a new array with items from the second array removed if it matches items in the first array.

For example, we can write the following:

import * as _ from "lodash";  
const comparator = (a, b) => a.id.toString() === b.id.toString();  
const result = _.differenceWith(  
  [{ id: 1 }, { id: 2 }],  
  [{ id: 1 }],  
  comparator  
);

The code above will compare the items from the first array with what’s in the second array and returned the items that aren’t in the second array in the new array according to the condition returned from the comparator function.

Then we get back:

[  
  {  
    "id": 2  
  }  
]

and assigned to result .

There’re some useful array methods in Lodash to make manipulating arrays easier.

The chunk method lets us separate array entries into arrays with the given size and returns it.

compact method creates an array with all the falsy values removed and returns it.

concat method creates a new array with the additional values added and returns it.

difference remove the values that are given in the values array in the 2nd argument from the original array. Similarly, differenceBy and differenceWith let us compare the arrays in different ways and manipulate them in different ways to eliminate elements from the original array that are given in the values array.

Categories
Express JavaScript

Guide to the Express Application Object — Rendering and Setting

The core part of an Express app is the Application object. It’s the application itself.

In this article, we’ll look at the methods of the app object and what we can do with it, including rendering HTML and changing settings.

app.render(view, [locals], callback)

We can use the app.render method to render HTML of a view via its callback function. It takes an optional parameter that’s an object containing variables for the view.

For example, we can use it as follows:

const express = require('express');  
const bodyParser = require('body-parser');  
const app = express();
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));
app.engine('ejs', require('ejs').renderFile);  
app.set('view engine', 'ejs');
app.render('index', { people: ['geddy', 'neil', 'alex'] }, (err, html) => {  
  console.log(html);  
});
app.listen(3000);

Then if we have the following in views/index.ejs :

<%= people.join(", "); %>

Then we get:

geddy, neil, alex

outputted from console.log(html);

app.route(path)

We can use app.route to define route handlers with the given path .

For example, we can use it as follows:

const express = require('express');  
const bodyParser = require('body-parser');  
const app = express();
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));
app.route('/')  
  .get((req, res, next) => {  
    res.send('GET request called');  
  })  
  .post((req, res, next) => {  
    res.send('POST request called');  
  })  
  .all((req, res, next) => {  
    res.send('Other requests called');  
  })app.listen(3000);

Then when a GET request is made to / , we get GET request called . If a POST request is made to / , then we get POST request called .

Any other kind of requests to / will get us Other requests called .

The order matters since all will handle all kinds of requests. So if we want to listen to specific kinds of requests in addition to other kinds of requests, all should come last.

app.set(name, value)

We can use set to set the setting with the given name to the given value .

For example, we can use it as follows:

const express = require('express');  
const bodyParser = require('body-parser');  
const app = express();
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));  
app.set('title', 'Foo');
app.get('/', (req, res) => {  
  res.send(app.get('title'));  
})
app.listen(3000);

Since we called app.set(‘title’, ‘Foo’); to set the title setting to Foo we should see Foo displayed when we make a GET request to / .

Some settings are special for Express. They include:

  • case sensitive routing — boolean value for enabling or disabling case sensitive routing (e.g. /Foo will be considered different from /foo if this is true )
  • env — string for the environment mode
  • etag — ETag response header
  • jsonp callback name — string for the JSONP callback name
  • json escape — boolean option to enable or disable escaping JSON response from res.json , res.jsonp or res.send . <, >, and & will be escaped if this is true
  • json replacer — replace callback for JSON.stringify
  • json spaces — spaces argument for JSON.stringify
  • query parser — disable query parsing if set to false , or set the query parse to use either 'simple' or 'extended' or a custom query string parsing function.
  • strict routing — boolean setting for enabling/disabling strict routing. If this is true , then /foo will be considered different from /foo/
  • subdomain offset — number of dot-separated parts of the host to remove to access subdomain. Defaults to 2.
  • trust proxy — indicates that the app is behind a proxy is it’s true . The X-Forwarded-* headers will determine the connection and IP address of the client.
  • views — string or array of directories to look for view templates. If it’s an array, then the views will be searched in the order they’re listed
  • view cache — boolean to enable view template compilation caching
  • view engine — string for setting view engine for rendering templates.
  • x-powered-by — enable 'X-Powered-By: Express HTTP header

Options for `trust proxy` setting

It can take on the following options:

  • true — client’s IP address is understood to be the leftmost entry of the X-Forwarded-* header
  • false — the app is assumed to be directly facing the Internet
  • String, comma-separated strings, or array of strings — one or more subnets or IP address to trust
  • Number — trust the nth hop from the front-facing proxy server as the client.
  • Function — custom trust implementation

Options for etag setting

It can take on the following options:

  • Boolean — true enables weak ETag, false disables ETag
  • String — 'strong' enables strong ETag, ‘weak’ enables weak ETag
  • Function — custom implementation.

Conclusion

We can render an HTML string with the app.render method. It takes a view file name, an object for variables and a callback with the html parameter to get the HTML rendered.

app.route lets us define route handlers.

app.set lets us set the options we want for our app. Some settings are special for Express and will be processed by it if they’re set.

Categories
JavaScript

More Handy JavaScript Shorthands

With the latest versions of JavaScript, the language has introduced more syntactic sugar. In this article, we’ll look at handy shortcuts that are easy to read from versions of JavaScript new and old. With them, it’ll save us time and make our code easier to read.

In this article, we’ll look at template strings, destructuring assignment, spread operator, exponentials, finding elements in arrays and dynamic keys in objects.

Template Literals

With ES6, we finally have string interpolation and multi-line strings with JavaScript that’s easy to use.

Template strings let us define strings that can have expressions inside and they can have as many lines as we want.

For example, we can write:

const name = 'Joe';  
const greeting = `Hi ${name}.`;

Then we can embed the value of name in our string.

It also works with expressions:

const likeApple = true;  
const greeting = `I like ${likeApple ? 'Apple' : 'Orange'}.`;

As we can see, we added the likeApple ? ‘Apple’ : ‘Orange’ expression into our string with the ${} characters wrapped around the expression.

They can also be multi-line:

const multiLine = `  
 Foo  
  Bar  
`;

Destructuring Assignment

We can decompose arrays and objects properties easily with the destructuring assignment shorthand.

To destructure arrays, we can write:

const fruits = ['apple', 'orange', 'banana'];  
const [apple, orange, banana] = fruits;

To assign 'apple' to apple , 'orange' to orange and 'banana' to banana .

We don’t have to assign every entry to a variable:

const fruits = ['apple', 'orange', 'banana'];  
const [apple, orange] = fruits;

In this case, we assign 'apple' to apple and 'orange' to orange .

We can do the same for objects. For example, we can write:

const obj = {  
  foo: 1,  
  bar: 2  
};  
const {  
  foo,  
  bar  
} = obj;

To decompose the properties of obj into variables with the same names as the property names.

To assign them to different variable names, we can write:

const obj = {  
  foo: 1,  
  bar: 2  
};  
const {  
  foo: a,  
  bar: b  
} = obj;

Then obj.foo will be assigned to a and obj.bar will be assigned to b .

Spread Operator

We can use the spread operator to merge arrays and objects.

For example, we can write:

const arr1 = [1, 2, 3];  
const arr2 = [4, 5, 6];  
const mergedArr = [...arr1, ...arr2];

It’s the same as using the concat method:

const arr1 = [1, 2, 3];  
const arr2 = [4, 5, 6];  
const mergedArr = arr1.concat(arr2);

It’s also good for cloning arrays:

const arr1 = [1, 2, 3];  
const arr2 = [...arr1];

It can be used anywhere in the array:

const arr1 = [1, 2, 3];  
const arr2 = [4, ...arr1, 5, 6];

Since ES2018, we can use it on objects as well:

const {  
  foo,  
  bar,  
  ...z  
} = {  
  foo: 1,  
  bar: 2,  
  c: 3,  
  d: 4  
};

We’ll get that foo is 1 and bar is 2 and z is {c: 3, d: 4}.

Check for Mandatory Parameters

Thanks to the default parameter value syntax, we can assign anything to parameters, including dynamic code.

This means that we can call a function to check if the value is passed in and throws an error if it isn’t.

For example, we can write:

const checkValue = () => {  
  throw new Error('Missing parameter');  
}const foo = (val = checkValue()) => val;

Then checkValue will run when foo is run.

Array.find

We can use the find method to search for the first entry that meets the condition that we specify.

For example, we can write:

const people = [{  
    name: 'Joe',  
    age: 10  
  },  
  {  
    name: 'Joe',  
    age: 11  
  },  
  {  
    name: 'Mary',  
    age: 13  
  },  
]
const joe = people.find(p => p.name === 'Joe');

Then we get that the value of joe is:

{name: "Joe", age: 10}

which is the first 'Joe' in the people array.

Dynamic Object Keys

We can write: obj.foo as obj['foo'] . This is handy for handling objects with dynamic keys.

It also works with object keys that are invalid as identifier names. For example, we can write:

obj['Jane Smith']

Since Jane Smith has a space inside it, it’s an invalid identifier, but we can still have a property name with spaces if we use a string.

With ES6 or later, we can define objects with dynamic property names:

const prop = 'prop';  
const obj = {  
  [prop]: 'foo'  
}

Property names can be strings or Symbols. Symbols are objects which its own use if for identifiers for functions.

For example, we can write:

const fn = Symbol('fn');  
const obj = {  
  [fn]() {  
    return 'foo';  
  }  
}

Exponential Operator

Latest versions of JavaScript has the exponential operator denoted by ** .

For example:

2**3

is the same as:

Math.pow(2,3);

The left operand is the base and the right one is the exponent.

ES6 or later has template strings, which lets us interpolate dynamic expressions and create multi-line strings.

We can create dynamic string or Symbols as object keys, which is handy for creating dynamic objects.

To check for mandatory parameters, we can run a function in the default parameter assignment code which throws an error.

The spread operator can be used to clone and combine arrays. Also, we can find the first entry that meets a condition with the Array.find method.

Categories
JavaScript Nodejs

Node.js FS Module — Opening Directories

Manipulating files and directories are basic operations for any program. Since Node.js is a server side platform and can interact with the computer that it’s running on directly, being able to manipulate files is a basic feature. Fortunately, Node.js has a fs module built into its library. It has many functions that can help with manipulating files and folders. File and directory operation that are supported include basic ones like manipulating and opening files in directories. Likewise, it can do the same for files. It can do this both synchronously and asynchronously. It has an asynchronous API that have functions that support promises. Also it can show statistics for a file. Almost all the file operations that we can think of can be done with the built in fs module. In this article, we will use the functions in the fs module to open and manipulate directories. We will also experiment with the fs promises API to do equivalent operations that exist in the regular fs module if they exist in the fs promises API. The fs promise API functions return promises so this let us run asynchronous operations sequentially much more easily.

Opendir Promise

The fs module can open, manipulate and close directories. Opening directories with the module is a simple task. To open a directory in a Node.js program, we can use the opendir function to do it. It takes a path object as an argument. The path can be a string, Buffer or an URL object. To open a directory, we can write the following code with the fs promise API, which is available in Node.js 12 LTS or later:

const fs = require("fs");

(async (path) => {  
  const dir = await fs.promises.opendir(path);  
  for await (const dirent of dir) {  
    console.log(dirent.name);  
  }  
})('./files');

The code above will list all the files and folders that are in the given folder. If you run the code above, you should get something like the following:

.keep  
file.txt  
file2.txt

Readdir

If you’re using a Node.js version that’s before 12, then we have to use the older fs API, which doesn’t have functions that return promises. We have to use the readdir function instead to list the contents of a directory. The readdir function takes 2 arguments. The first is the path object, which can be a string, an URL object or a Buffer, and the second argument is a callback function that’s called when the result is produced. The first parameter of the callback is the error object which is defined when there’s an error, and the second is an array with the actual results. For example, if we want to view the content of the ./files folder, we can write:

const fs = require("fs");

fs.readdir("./files", (err, items) => {  
  for (const dirent of items) {  
    console.log(dirent);  
  }  
});

The code above will get us similar output if we run it. It will open the directory path asynchronously, and then list the contents when it’s ready. If we have the same content as the directory above, we will see the following:

.keep  
file.txt  
file2.txt

There’s also a synchronous version of the readdir function called the readdirSync . It takes one argument, which is the path object, which can be a string, an URL object or a Buffer. It returns an array with the content of the given directory path. We can do the same thing by writing the following code:

const fs = require("fs");

const items = fs.readdirSync("./files");  
for (const dirent of items) {  
  console.log(dirent);  
}

If we run the code above, we get the same output as we did before if we have the same contents in the given directory as before.

The opendir function and its synchronous version opendirSync function let us get the directory resource handle of the folder with the given path object. The path object can be a string, an URL object or a buffer. Then asynchronous version, opendir , takes the path object as the first argument and callback function which takes the error object as the first parameter and the directory resource handle object as the second parameter. It’s called when the directory is opened. With the directory handle

Whenever you’re done with opening the directory with the opendir, opendirSync, and manipulating it, we should close it to clean up any reference of it from memory to prevent memory leaks. To do this, Node.js has a close function, which takes a callback function with an error object parameter to get the error when there’s one. It will close the open directory’s resource handle asynchronously. There’s also a synchronous version called the closeSync function that takes no arguments and closes the directory’s resource handle like the close function did, but it holds up the Node.js program’s process until it’s finished. This doesn’t apply to the fs promise API version of opendir since it closes it automatically. For example, if we want to open a directory asynchronously, we can write:

fs.opendir("./files", (err, dir) => {  
  console.log(dir);  
  dir.read((err, dirent) => {  
    console.log(dirent);  
    dir.close();  
  });  
});

The code above will open the directory with the opendir function, which takes a path object and a callback that takes an error object and the directory handle as parameters. Then we call the read function to open the directory and get its description and the name..

Then we call close on the directory resource handle object in the callback passed into the read function which closes the resource and frees up the memory. If we run it, we will get output the looks something like the following:

Dir {  
  [Symbol(kDirHandle)]: DirHandle {},  
  [Symbol(kDirPath)]: './files',  
  [Symbol(kDirClosed)]: false,  
  [Symbol(kDirOptions)]: { encoding: 'utf8' },  
  [Symbol(kDirReadPromisified)]: [Function: bound read],  
  [Symbol(kDirClosePromisified)]: [Function: bound close]  
}  
Dirent { name: '\u0010S.u\u0001', [Symbol(type)]: 777167552 }

OpendirSync

A synchronous version of the opendir function, which is the opendirSync function, can be used with the readSync function to get the directory’s metadata. For example, we can write:

const fs = require("fs");const dir = fs.opendirSync("./files");  
const dirData = dir.readSync();  
console.log(dirData)  
dir.closeSync();

The dirData variable will have something like the following output:

Dirent { name: '.keep', \[Symbol(type)\]: 1 }

That is the data of the content of the directory. To get the path of the opened directory, we can use the path function, which is a function that’s part of the directory object. For example, we can write the following to get the path of the currently opened directory:

const fs = require("fs");fs.opendir("./files", (err, dir) => {  
  console.log(dir.path);  
});

If we run the code above, the we will get output that’s similar to the following:

./files

The output row is the output of the first console.log statement, which is the path of the currently open directory. This isn’t very useful here, but it can be used when the directory resource handle is from an indefinite origin, like when the directory resource handle object is passed in as an argument of a function.

To read the contents of the directory with a directory resource handle, we can use the read function, which is part of the directory resource handle object.

It takes no arguments and a promise is returned that’ll be resolved with the fs.Dirent object, which is an iterable object that has the names of the items in a directory.

The read function without any arguments returns a promise that resolves with the same Dirent object as the example above. For example, we can use the read like in the following code with the asynchronous opendir function:

const fs = require("fs");fs.opendir("./files", (err, dir) => {  
  dir.read((err, dirent) => {  
    console.log(dirent);  
    dir.close();  
  });  
});

If we run the code, we get something like the following output:

Dirent { name: '.keep', \[Symbol(type)\]: 1 }

The output above has the Dirent object, which has the name of the first file in the directory.

<img class="s t u gw ai" src="https://miro.medium.com/max/5854/0*M3wUa7pqdaGu7xMY" width="2927" height="3903" srcSet="https://miro.medium.com/max/552/0*M3wUa7pqdaGu7xMY 276w, https://miro.medium.com/max/1104/0*M3wUa7pqdaGu7xMY 552w, https://miro.medium.com/max/1280/0*M3wUa7pqdaGu7xMY 640w, https://miro.medium.com/max/1400/0*M3wUa7pqdaGu7xMY 700w" sizes="700px" role="presentation"/>

Photo by Omid Kashmari on Unsplash

Listing Multiple Pieces of Directory Content with Opendir

We can read more than one file in the directory, by nested the read function in the callback of the outer read function. For example, we can write:

const fs = require("fs");fs.opendir("./files", (err, dir) => {  
  console.log(dir.path);  
  dir.read((err, dirent) => {  
    console.log(dirent);  
    dir.read((err, dirent) => {  
      console.log(dirent);  
      dir.close();  
    });  
  });  
});

Then we get output with something like the following text:

./files  
Dirent { name: '.keep', \[Symbol(type)\]: 1 }  
Dirent { name: 'file.txt', \[Symbol(type)\]: 1 }

The first row of the output contains the folder path, which we got with dir.path . The next 2 rows are the first 2 items of the directory. Every time we call dir.read , we get the next item of the directory.

To read the contents of the directory with a directory resource handle, we can use the read function, which is part of the directory resource handle object. It takes no arguments and a promise is returned that’ll be resolved with the fs.Dirent object, which is an iterable object that has the names of the items in a directory. The read function without any arguments returns a promise that resolves with the same dirent object as the example above. For example, we can use the read like in the following code with the asynchronous opendir function:

const fs = require("fs");fs.opendir("./files", async (err, dir) => {  
  console.log(dir.path);  
  const item = await dir.read();  
  console.log(item)  
  dir.close();  
});

If we run the code above, we get something like the following:

./files  
Dirent { name: '.keep', \[Symbol(type)\]: 1 }

If we want to get the first 2 items in the directory, with the promise version of dir.read , we can write the following:

const fs = require("fs");fs.opendir("./files", async (err, dir) => {  
  console.log(dir.path);  
  const item1 = await dir.read();  
  console.log(item1)  
  const item2 = await dir.read();  
  console.log(item2)  
  dir.close();  
});

We should get the same output as what we had above assuming we got the same folder contents as before. As we can see, it’s not practical to use those methods to get more items inside the directory those 2 examples as have above of the read function. If we want to get more than 2 items in the directory with the read function, we can write the following with the promise version of the read function, which takes no arguments:

const fs = require("fs");fs.opendir("./files", async (err, dir) => {  
  while ((item = await dir.read())) {  
    console.log(item);  
  }  
  dir.close();  
});

If we run the code above, we get something like the following output:

Dirent { name: '.keep', \[Symbol(type)\]: 1 }  
Dirent { name: 'file.txt', \[Symbol(type)\]: 1 }  
Dirent { name: 'file2.txt', \[Symbol(type)\]: 1 }  
Dirent { name: 'folder1', \[Symbol(type)\]: 2 }  
Dirent { name: 'folder2', \[Symbol(type)\]: 2 }

Note that we can use the await keyword inside a while loop to repeatedly run the dir.read() function call until null or undefined is returned. In the code above, we looped through all the items in the directory and logged the content of the Dirent object.

To check if a Dirent object is a directory, we can use the isDirectory() function. Likewise, we can check if an Dirent is a file with the isFile() function. For example, we can write the following to check if a Dirent is a file or a folder for the contents of a given directory with the following code:

const fs = require("fs");

fs.opendir("./files", async (err, dir) => {  
  while ((item = await dir.read())) {  
    console.log(item);  
    console.log(`Is directory: ${item.isDirectory()}`);  
    console.log(`Is file: ${item.isFile()}\n`);  
  }  
  dir.close();  
});

When we run the code above, we get something like the following output:

Dirent { name: '.keep', [Symbol(type)]: 1 }  
Is directory: false  
Is file: trueDirent { name: 'file.txt', [Symbol(type)]: 1 }  
Is directory: false  
Is file: trueDirent { name: 'file2.txt', [Symbol(type)]: 1 }  
Is directory: false  
Is file: trueDirent { name: 'folder1', [Symbol(type)]: 2 }  
Is directory: true  
Is file: falseDirent { name: 'folder2', [Symbol(type)]: 2 }  
Is directory: true  
Is file: false

As we can see, the isDirectory and isFile functions can identify if an item in a directory is another directory and it can also identify whether it’s a file or not.

With the Node.js’ built in fs module, we can open directories and list its contents easily. It has many functions that can help with opening directories and files inside it. It can do this both synchronously and asynchronously. It has an asynchronous API that have functions that support promises.

Also, it can show statistics for a file. Almost all the file operations that we can think of can be done with the built-in fs module. In this article, we used the functions in the fs module to open directories and list directory contents.

We also used some functions in the fs module that returns promises. The fs functions that return promises let us run asynchronous operations sequentially much more easily.