Categories
JavaScript Answers

How to check that two objects have the same set of property names with JavaScript?

To check that two objects have the same set of property names with JavaScript, we use the Object.keys method.

For instance, we write

const compareKeys = (a, b) => {
  const aKeys = Object.keys(a).sort();
  const bKeys = Object.keys(b).sort();
  return JSON.stringify(aKeys) === JSON.stringify(bKeys);
};

to define the compareKeys function.

In it, we get the keys of objects a and b with Object.keys in an array.

Then we sort both arrays with sort.

Then we convert both arrays to JSON strings with JSON.stringify and compare to see if they’re equal.

Categories
JavaScript Answers

How to use webpack with Node Express?

To use webpack with Node Express, we create a config that builds with 'node' as its target.

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

module.exports = [
  {
    name: "server",
    entry: "./src/server/index.js",
    target: "node",
    output: {
      path: __dirname + "/dist/server",
      filename: "bundle.js",
    },
  },
  {
    name: "client",
    entry: "./src/client/index.js",
    // target: 'web', // by default
    output: {
      path: __dirname + "/dist/client",
      filename: "bundle.js",
    },
  },
];

to set the target property to 'node' in the first object to set the build target of the server app to Node.

We set the entry property to the entry point file path.

And we set the output property to an object with the bundle file path.

Categories
JavaScript Answers

How to fix npm ERR! network getaddrinfo ENOTFOUND error with JavaScript?

To fix npm ERR! network getaddrinfo ENOTFOUND error with JavaScript, we fix the proxy settings.

For instance, we run

npm config set proxy http://domain:8080

to run npm config set proxy to make npm use the correct proxy URL.

Categories
JavaScript Answers

How to do array with object sorting with JavaScript Underscore sortBy?

To do array with object sorting with JavaScript Underscore sortBy, we call sortBy with the array and a callback to return the field to sort by.

For instance, we write

const sorted = _.sortBy(arr, (o) => {
  return o.start.dateTime;
});

to call sortBy with arr and a callback that returns the start.dateTime property from the object to sort by this property.

An array with the sorted objects is returned.

Categories
JavaScript Answers

How to know if a request is http or https in Node.js?

To know if a request is http or https in Node.js, we use the req.secure property.

For instance, we write

const isSecure = req.secure;

to check if the request is secure with the req.secure property.

If it’s true, then the request is made via https.