Categories
Node.js Tips

Node.js Tips — Modules, Hashes, Favicons, Nested Routers

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Generate Random SHA1 Hash to Use as ID in Node.js

To generate a random SHA1 hash, we can use the crypto module.

For instance, we can write:

const crypto = require('crypto');
const currentDate = (new Date()).getTime().toString();
const random = Math.random().toString();
crypto.createHash('sha1').update(currentDate + random).digest('hex');

We use the getTime method of the Date instance to get the timestamp.

Then we create a random number.

Next, we create the hash by using the crypto module’s createHash and update methods to create the hash.

Then we convert that to hex with digest .

Set Custom Favicon in Express

We can serve a custom favicon by using the serve-favicon package.

For example, we can write:

const favicon = require('serve-favicon');
app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));

The package is installed by running:

npm i serve-favicon

Then we can use the bundled middleware by passing in the path of the middleware.

Open Default Browser and Navigate to a Specific URL in a Node App

We can use the opn package to open the browser and go to a specific URL.

To install it, we run:

npm install opn

Then we can write:

const opn = require('opn');
opn('http://example.com');

to open the URL with the default browser.

We can also specify the browser by writing:

opn('http://example.com', { app: 'firefox' });

Then the URL will open in Firefox.

Express.js with Nested Router

We can nest routers Express.

For instance, we can write:

const express = require('express');
const app = express();

const userRouter = express.Router();
const itemRouter = express.Router({ mergeParams: true });

userRouter.use('/:userId/items', itemRouter);

userRouter.route('/')
  .get((req, res) `=>` {
    res.send('hello users');
  });

userRouter.route('/:userId')
  .get((req, res) `=>` {
    res.status(200)
  });

itemRouter.route('/')
  .get((req, res) `=>` {
    res.send('hello');
  });

itemRouter.route('/:itemId')
  .get((req, res) => {
    res.send(`${req.params.itemId} ${req.params.userId}`);
  });

app.use('/user', userRouter);

app.listen(3000);

We just pass the router items to the place we wish.

mergeParams is need on the itemRouter since we want to access parameters from the parent router.

Other than that, we just nest itemRouter in userRouter by writing:

userRouter.use('/:userId/items', itemRouter);

Convert a Binary NodeJS Buffer to JavaScript ArrayBuffer

We can convert a Node buffer to a JavaScript ArrayBuffer by writing:

const toArrayBuffer = (buffer) => {
  const arrayBuffer = new ArrayBuffer(buffer.length);
  const view = new Uint8Array(arrayBuffer);
  for (let i = 0; i < buffer.length; i++) {
    view[i] = buffer[i];
  }
  return arrayBuffer;
}

We just put each but of the buffer into the Uint8Array .

We can convert the other way by writing:

const toBuffer = (arrayBuffer) => {
  const buffer = Buffer.alloc(arrayBuffer.byteLength);
  const view = new Uint8Array(arrayBuffer);
  for (let i = 0; i < buffer.length; i++) {
    buffer[i] = view[i];
  }
  return buffer;
}

We create the Buffer with the alloc method.

Then we pass the arrayByffer to the Uint8Array constructor so we can loop through it.

Then we assign all the bits to the buffer array.

Create Directory When Writing To File In Node Apps

We can use the recursive option for the fs.mkdir method to create a directory before creating the file.

For instance, we can write:

fs.mkdir('/foo/bar/file', { recursive: true }, (err) => {
  if (err) {
    console.error(err);
  }
});

We create the file with path /foo/bar/file since we have the recursive option set to true .

Also, we can use the promise version by writing:

fs.promises.mkdir('/foo/bar/file', { recursive: true }).catch(console.error);

Load External JS File in with Access to Local Variables

We can load external JS files from another file if we create a module.

For instance, we can write:

module.js

module.exports = {
  foo(bar){
    //...
  }
}

app.js

const module = require('./module');
module.foo('bar');

We export the foo function by putting it in module.exports and import it with require .

Then we call it with module.foo('bar'); .

Conclusion

We can use the crypto module to generate a hash with a timestamp and a random string.

Also, we can convert between a Node buffer and an ArrayBuffer with loops.

The serve-favicon package lets us serve favicons in our Express apps.

We can create modules to export functions that can be run from other functions.

Express routers can be nested more than one level deep.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *