Categories
JavaScript Answers

How to generate timestamp unix epoch format with Node.js?

To generate timestamp unix epoch format with Node.js, we use the Date constructor.

For instance, we write

const ts = Math.floor(new Date().getTime() / 1000);

to create a new date with the current date and time with the Date constructor.

Then we call getTime to get its timestamp in milliseconds.

And then we divide that by 1000 to get the timestamp in seconds.

Finally, we call Math.floor with the timestamp in seconds to round it down to the nearest integer.

Categories
JavaScript Answers

How to chain multiple pieces of middleware for specific route in Node.js Express?

To chain multiple pieces of middleware for specific route in Node.js Express, we put the middlewares in an array.

For instance, we write

const middleware = {
  requireAuthentication: (req, res, next) => {
    console.log("private route list!");
    next();
  },
  logger: (req, res, next) => {
    console.log("Original request hit : " + req.originalUrl);
    next();
  },
};

app.get(
  "/",
  [middleware.requireAuthentication, middleware.logger],
  (req, res) => {
    res.send("Hello!");
  }
);

to add the middlewares into the middleware object.

Then we call app.get with an array with the middlewares as the 2nd argument to call them in the same order they’re listed before calling the route handler.

Categories
JavaScript Answers

How to use a variable as a field name in mongodb-native findOne() with JavaScript?

To use a variable as a field name in mongodb-native findOne() with JavaScript, we call use a computed property name.

For instance, we write

const name = req.params.name;
const value = req.params.value;
collection.findOne({ [name]: value }, (err, item) => {
  res.send(item);
});

to call findOne with an object that has the name value as the property name.

Then we get the result from item in the callback.

Categories
JavaScript Answers

How to kill child process in Node.js?

To kill child process in Node.js, we call the kill method.

For instance, we write

const proc = require("child_process").spawn("mongod");
proc.kill("SIGINT");

to call spawn to run the mongod program.

Then we call kill with 'SIGINT' to kill the process.

Categories
JavaScript Answers

How to join tests from multiple files with mocha.js and JavaScript?

To join tests from multiple files with mocha.js and JavaScript, we use the --recursive option to run all test files in the project.

To do this, we run

$ mocha --recursive

to make mocha find all tests in the project folder and run them.