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.

Categories
JavaScript Answers

How to fix Cannot find type definition file for ‘node’ error?

To fix Cannot find type definition file for ‘node’ error, we install the Node type definitions.

To do this, we run

npm install @types/node --save-dev

to install the Node type definition by install @types/node as a dev dependency.

Categories
JavaScript Answers

How to store objects in Node.js redis?

To store objects in Node.js redism we call the hmset method.

For instance, we write

client.hmset("hosts", "mjr", "1", "another", "23", "home", "1234");

client.hgetall("hosts", (err, obj) => {
  console.dir(obj);
});

to call hmset with the key 'hosts' and the subsequent arguments as key-value pairs.

Then we get the value with with key 'hosts' with hgetall.

We get the value from obj in the callback.

Categories
JavaScript Answers

How to store a file with file extension with Node multer?

To store a file with file extension with Node multer, we set the filename property to a function that returns the file name with the extension.

For instance, we write

const multer = require("multer");
const path = require("path");

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));
  },
});

const upload = multer({ storage });

to set the filename property of the object we call diskStorage with to return the file name by calling cb with path.extname(file.originalname) to include the extension.