Categories
JavaScript Answers

How to sleep the thread in Node.js without affecting other threads?

To sleep the thread in Node.js without affecting other threads, we use the setTimeout function.

For instance, we write

const snooze = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const example = async () => {
  console.log("About to snooze without halting the event loop...");
  await snooze(1000);
  console.log("done!");
};

example();

to define the snooze function.

In it, we return a promise that calls setTimeout with resolve as its callback after ms milliseconds to settle the promise after ms milliseconds.

Then we call snooze in the example function and use await to wait for the promise to finish.

Categories
JavaScript Answers

How to query for distinct values in Mongoose and Node?

To query for distinct values in Mongoose and Node, we call the distinct method.

For instance, we write

MyModel.find().distinct("_id", (error, ids) => {
  // ...
});

to call distinct to return an array of distinct values.

We get the entries that have distinct _id values.

And then we get the _id values from ids in the callback.

Categories
JavaScript Answers

How to loop through dynamic test cases with Jest and JavaScript?

To loop through dynamic test cases with Jest and JavaScript, we use the each method.

For instance, we write

test.each([
  [1, 1, 2],
  [1, 2, 3],
  [2, 1, 3],
])(".add(%i, %i)", (a, b, expected) => {
  expect(a + b).toBe(expected);
});

to call test.each with an array of arguments for the callback.

In the callback, we add the test code that uses the parameters.

Categories
JavaScript Answers

How to write a line into a .txt file with Node.js?

To write a line into a .txt file with Node.js, we call the appendFile function.

For instance, we write

const fs = require("fs");

fs.appendFile("log.txt", "new data", (err) => {
  if (err) {
    // append failed
  } else {
    // done
  }
});

to call appendFile to append 'new data' to log.txt.

And we get the error from err if there’re any errors.

Categories
JavaScript Answers

How to fix writeFile no such file or directory error with Node?

To fix writeFile no such file or directory error with Node, we call the mkdirp function to create the directory if it doesn’t exist.

For instance, we write

const mkdirp = require("mkdirp");
const fs = require("fs");

const writeFile = async (path, content) => {
  await mkdirp(path);
  fs.writeFileSync(path, content);
};

to define the writeFile function.

In it, we call mkdirp to create the directory at the path if it doesn’t exist.

Then we call writeFileSync to write the file to the path.