Categories
JavaScript Answers

How to send a custom HTTP status message in Node Express?

To send a custom HTTP status message in Node Express, we call send with the message.

For instance, we write

res.status(400).send('Current password does not match');

to call send with the status message after call status to send the response with code 400.

Categories
JavaScript Answers

How to fix ‘node’ is not recognized as an internal or an external command, operable program or batch file error while using Phonegap/Cordova with JavaScript?

To fix ‘node’ is not recognized as an internal or an external command, operable program or batch file error while using Phonegap/Cordova with JavaScript, we add the Node.js executable directory to the PATH environment variable.

For instance, we run

SET PATH=C:\Program Files\Nodejs;%PATH%

to add the Node.js excutable directory to the PATH environment variable on Windows with the SET command.

Categories
JavaScript Answers

How to drop a database with Mongoose and JavaScript?

To drop a database with Mongoose and JavaScript, we use the Mongo native driver’s drop method.

For instance, we write

mongoose.connection.collections["collectionName"].drop((err) => {
  console.log("collection dropped");
});

to get the Mongo collection with collections.

And we call drop with a callback that’s called when there’s an error to drop the collectionName collection.

Categories
JavaScript Answers

How to get a microtime in Node.js?

To get a microtime in Node.js, we use the performance-now module.

For instance, we write

const loadTimeInMS = Date.now();
const performanceNow = require("performance-now");
console.log((loadTimeInMS + performanceNow()) * 1000);

to call performanceNow to get the current timestamp in milliseconds.

We multiply it by 1000 to get the value in microseconds.

Categories
JavaScript Answers

How to read the body of a Fetch Promise with JavaScript?

To read the body of a Fetch Promise with JavaScript, we use await.

For instance, we write

const response = await fetch("https://api.ipify.org?format=json");
const data = await response.json();
console.log(data);

to call fetch to make a get request and return a promise with the response.

We use await to get the result of the returned promise.

Then we call response.json to get the response as JSON.

We use await to get the result of the promise returned by json.

We put the code in an async function.