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.

Categories
JavaScript Answers

How to run shell script file using Node?

To run shell script file using Node, we use the exec function.

For instance, we write

const { exec } = require("child_process");
const yourscript = exec("sh hi.sh", (error, stdout, stderr) => {
  console.log(stdout);
  console.log(stderr);
  if (error !== null) {
    console.log(`exec error: ${error}`);
  }
});

to call exec to rub the sh hi.sh command.

We get the output from the stdout parameter in the callback.

And we get error output from the stderr parameter in the callback.

Categories
JavaScript Answers

How to tell npm to use a different version of one of its dependencies when installing a package?

To tell npm to use a different version of one of its dependencies when installing a package, we put the version number after the @.

For instance, we run

npm install module@0.0.2

to run npm install to install module module version 0.0.2.