Categories
JavaScript Answers

How to get the sha1 hash of a string in Node.js?

To get the sha1 hash of a string in Node.js, we use the crypto module.

For instance, we write

const crypto = require("crypto");
const shasum = crypto.createHash("sha1");
shasum.update("foo");
const hash = shasum.digest("hex");

to call createHash to create a hash.

Then we call update to add content to it.

Finally, we call digest with 'hex' to return the hash.

Categories
JavaScript Answers

How to create a Express.js middleware that accepts parameters with JavaScript?

To create a Express.js middleware that accepts parameters with JavaScript, we return a function that takes the arguments we want.

For instance, we write

const hasRole = (role) => {
  return (req, res, next) => {
    if (role !== req.user.role) {
      res.redirect("...");
    } else {
      next();
    }
  };
};

const middlwareHasRoleAdmin = hasRole("admin");

app.get("/hasToBeAdmin", middlwareHasRoleAdmin, (req, res) => {});

to define the hasRole function.

It returns a middleware function that checks the role and either redirects with res.redirect or move to the next middleware with next.

Then we call hasRole with 'admin' to return a middleware with role set to 'admin'.

And we use the middlwareHasRoleAdmin middleware in our /hasToBeAdmin route.

Categories
JavaScript Answers

How to install only “devDependencies” using npm?

To install only "devDependencies" using npm, we use the --only-dev option.

To use it, we run

npm install --only=dev

to use the --only-dev option to only install dev dependencies.

Categories
JavaScript Answers

How to install Node.js as windows service?

To install Node.js as windows service, we use the node-windows package.

For instance, we write

const Service = require("node-windows").Service;

const svc = new Service({
  name: "Hello World",
  description: "The nodejs.org example web server.",
  script: "C:\\path\\to\\helloworld.js",
});

svc.on("install", () => {
  svc.start();
});

svc.install();

to create a Service object with the name, description and the program location.

Then we listen for the install event with on and call start to start the service once it’s installed.

Finally, we call install to install the service.

Categories
JavaScript Answers

How to include JavaScript class definition from another file in Node.js?

To include JavaScript class definition from another file in Node.js, we set the class as the value of module.exports.

For instance, in user.js, we write

class User {
  //...
}

module.exports = User;

to export the User class.

Then in app.js, we write

const User = require("./user.js");

let user = new User();

to import the user.js file with required.

And then we create a User object.