Categories
JavaScript Answers

How to create an ISO date object in JavaScript?

To create an ISO date object in JavaScript, we call the toISOString method.

For instance, we write

const isoDate = new Date().toISOString();

to create a date with the Date constructor.

And then we call toISOString to return the ISO string version of the date and time.

Categories
JavaScript Answers

How to get the npm global path prefix with Node?

To get the npm global path prefix with Node, we run npm config.

To do this, we run

npm config get prefix

to return the global package path prefix.

Categories
JavaScript Answers

How to remove everything after last backslash with JavaScript?

To remove everything after last backslash with JavaScript, we call the substr and lastIndexOf methods.

For instance, we write

const t = "\\some\\route\\here";
const newT = t.substr(0, t.lastIndexOf("\\"));

to call lastIndexOf to return the last index of '\\'.

Then we call substr to return the substring in t before index 0 and the index returned by lastIndexOf.

Categories
JavaScript Answers

How to run Node.js app forever when console is closed?

To run Node.js app forever when console is closed, we use the forever package.

For instance, we run

sudo npm install -g forever

to install forever globally.

Then we run server.js even when the console is closed with

forever start server.js

And we stop it with

forever stop server.js

We see the list of running processes with

forever list
Categories
JavaScript Answers

How to get a JSON via HTTP request in Node?

To get a JSON via HTTP request in Node, we call request with an object with the json property set to true.

For instance, we write

const options = {
  hostname: "127.0.0.1",
  port: app.get("port"),
  path: "/users",
  method: "GET",
  json: true,
};
request(options, (error, response, body) => {
  if (error) {
    console.log(error);
  } else {
    console.log(body);
  }
});

to call request with an object with the json property set to true.

We make a get request to the URL we get from the hostname, port, and path.

Since we get json to true, the response we get from the body parameter is a plain JavaScript object.