Categories
JavaScript Answers

How to spawn and kill a process in Node.js?

To spawn and kill a process in Node.js, we use the tree-kill package.

For instance, we write

const kill = require("tree-kill");
const spawn = require("child_process").spawn;

const scriptArgs = ["myScript.sh", "arg1", "arg2", "youGetThePoint"];
const child = spawn("sh", scriptArgs);

button.on("someEvent", () => {
  kill(child.pid);
});

to call spawn to run the 'sh' command with the scriptArgs command line arguments.

And then we call kill to kill the process with the child.pid process ID.

Categories
JavaScript Answers

How to fix Node cannot find module “fs” when using Webpack?

To fix Node cannot find module "fs" when using Webpack, we set target to 'node'.

For instance, in webpack.config.js, we write

module.exports = {
  entry: "./app",
  output: {
    path: __dirname,
    filename: "bundle.js",
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: "node_modules",
        loader: "babel",
        query: { presets: ["es2015"] },
      },
    ],
  },
  target: "node",
};

to set target to 'node' to make Webpack build for Node.js instead of browser.

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.