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.

Categories
JavaScript Answers

How to fix JavaScript ES6 TypeError: Class constructor Client cannot be invoked without ‘new’?

To fix JavaScript ES6 TypeError: Class constructor Client cannot be invoked without ‘new’, we should set the build target to a recent version of JavaScript.

For instance, we write

{
  //...
  "compilerOptions": {
    "target": "ES2017"
  }
}

in tsconfig.json to set the TypeScript compiler build target to ES2017 to avoid transpilation of ES6 classes to ES5 constructor functions that cause this error.

Categories
JavaScript Answers

How to time out a Node Promise if failed to complete in time?

To time out a Node Promise if failed to complete in time, we use the Promise race method.

For instance, we write

const race = Promise.race([
  new Promise((resolve) => {
    setTimeout(() => {
      resolve("I did it");
    }, 1000);
  }),
  new Promise((resolve, reject) => {
    setTimeout(() => {
      reject("Timed out");
    }, 800);
  }),
]);

try {
  const data = await race;
} catch (e) {
  console.log(e);
}

to call Promise.race with an array of promises.

We call reject in the 2nd Promise callback to reject the promise after 800ms.

Then we use await to run the promise returned by race.

And then we get the data from the promise.

We catch the rejection with the catch block.

Categories
JavaScript Answers

How to fix TypeError: db.collection is not a function with Node MongoDB?

To fix TypeError: db.collection is not a function with Node MongoDB, we should make sure we’re getting the collection from the database object.

For instance, we write

MongoClient.connect(db.url, (err, database) => {
  const myAwesomeDB = database.db("myDatabaseNameAsAString");
  myAwesomeDB.collection("theCollectionIwantToAccess");
});

to call connect to connect to the database.

And we get the database from the database.db method.

We then get the collection from the database’s collection property.