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.

Categories
JavaScript Answers

How to close a readable stream before end with Node.js?

To close a readable stream before end with Node.js, we call the destroy method.

For instance, we write

const fs = require("fs");

const readStream = fs.createReadStream("lines.txt");
readStream
  .on("data", (chunk) => {
    console.log(chunk);
    readStream.destroy();
  })
  .on("end", () => {
    console.log("All the data in the file has been read");
  })
  .on("close", (err) => {
    console.log("Stream has been destroyed and file has been closed");
  });

to create the readStream with createReadStream.

Then we call destroy in the data event handler to close the read stream.

Categories
JavaScript Answers

How to stub a class method with Sinon.js and JavaScript?

To stub a class method with Sinon.js and JavaScript, we call the stub method.

For instance, we write

sinon.stub(YourClass.prototype, "myMethod").callsFake(() => {
  return {};
});

to call stub with YourClass.prototype to stub the myMethod instance method on YourClass.

We call callFake with the mock function for the myMethod method.

Likewise, for static class methods, we write

sinon.stub(YourClass, "myStaticMethod").callsFake(() => {
  return {};
});

to mock the YourClass.myStaticMethod static method with stub.