Categories
Node.js Tips

Node.js Tips — Start Scripts, Object IDs, and Logging

Spread the love

As with many types 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.

npm start vs node app.js

npm start can be run when we put a start script in the package.json .

In package.json , we’ve to add a script like:

{
  ...
  `"scripts": {
    "start": "node index.js"
  }
  ...
}`

Then we can run npm start , which runs node index.js .

npm start can run any script.

On the other hand, node app.js just runs app.js with node .

It’s always the same.

Convert a String to ObjectId in Node.js MongoDB Native Driver

We can convert a string to an object ID with the Node MongoDB driver by using the ObjectId function from the mongodb package.

For instance, we can write:

const {ObjectId} = require('mongodb');

const updateStuff = (id, doc) => {
  if (!ObjectId.isValid(s)) {
    return Promise.reject(new Error('invalid id'));
  }
  return collection.findOneAndUpdate(
    { _id: ObjectId(id) },
    { $set: doc },
    { returnOriginal: false }
  );
};

We check if the string is a valid object ID with the ObjectId.isValid method. If it is, then we call findOneAndUpdate to do the update. We’ve to convert the id string to an object ID with the ObjectId function.

Create a Sleep or Delay Function in Node.js that is Blocking

If we want a synchronous sleep or delay function in Node, we can create a loop that runs until a given the time span has elapsed.

For instance, we can write:

const sleep = (time) => {
  const stop = new Date().getTime();
  while(new Date().getTime() < stop + time) {

  }
}

We just create a while loop with an empty body that runs until the timestamp is stop + time .

This is a synchronous sleep function that blocks the rest of the app from running. Therefore, we probably shouldn’t use it in most apps.

Global Modules

We can require a module and set it to a global variable.

For instance, we can write:

global.util = require('util');

We can set the util module as a global variable, but we probably shouldn’t do that since it doesn’t bring any advantages over importing modules. And we don’t know what’s in the global object if we do that a lot.

How to Generate Timestamp UNIX epoch format Node.js

To generate timestamp as a UNIX epoch, we can use the Date constructor.

For instance, we can write:

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

new Date() returns the UNIX epoch in milliseconds.

We can divide it by 1000 to get the epoch in seconds.

And we use Math.floor to round it down to the nearest integer.

Asynchronous Module Loading with Node.js

We can make require asynchronous by creating our own module that can load asynchronously.

For instance, we can write:

bar.js

const fs = require('fs');
module.exports = (callback) => {
  fs.readFile('/foo/bar', (err, data) => {
    callback(err, data);
  });
};

We call readFile to read the content of /foo/bar and calls the callback which has the data read from the file.

We call callback inside it so that we can use it outside of the readFile callback.

Then we can use bar.js by writing:

require('./bar')((err, bar) => {
  // ...
});

We require bar.js with require .

Then we call the required function with our own callback to get the data from bar.js via the bar parameter.

Difference Between console.log and sys.puts in Node.js

sys.puts can’t print the content of objects. It just prints the string passed into it in the logs. It’s also deprecated so it shouldn’t be used. console.log can print the content of arrays and objects. It’s not deprecated so it’s safe to use in our apps.

Conclusion

npm start runs the script named start from package.json . We can check if a string is a valid object ID before converting it to such. sys.puts shouldn’t be used since the sys module is deprecated. We can generate a timestamp with the Date constructor. To read modules asynchronously, we can use readFile to read the content. We shouldn’t use synchronous log functions even if we can write one.

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 *