Categories
JavaScript Answers

How to add global variables for Node.js standard modules?

To add global variables for Node.js standard modules, we export the variables.

For instance, we write

const common = {
  util: require("util"),
  fs: require("fs"),
  path: require("path"),
};

module.exports = common;

to export the common object by setting it as the value of module.exports in common.js.

Then we write

const common = require("./common.js");
console.log(common.util.inspect(common));

to call require to include the exports in common.js in our code.

Categories
JavaScript Answers

How to get Node Socket.IO connected user count?

To get Node Socket.IO connected user count, we use the socketIO.engine.clientsCount property.

For instance, we write

const numClients = socketIO.engine.clientsCount;

to get the number of clients connected with socketIO.engine.clientsCount.

Categories
JavaScript Answers

How to fix ECONNREFUSED error when connecting to MongoDB from Node.js?

To fix ECONNREFUSED error when connecting to MongoDB from Node.js, we call connect.

For instance, we write

const mongoose = require("mongoose");

const mongoURI = "mongodb://localhost:27017/test";
const MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on("error", (err) => {
  console.log(err.message);
});
MongoDB.once("open", () => {
  console.log("mongodb connection open");
});

to call connect to connect to MongoDB with the mongoURI.

We get the connection with the connection property.

And we call on to catch errors.

We call once to catch the first emission of the open event.

Categories
JavaScript Answers

How to fix install Node npm package fails with 404?

To fix install Node npm package fails with 404, we set the npm registry.

For instance, we run

npm config set registry http://registry.npmjs.org

to run npm config set registry to set the package registry URL to the default npm registry URL.

Categories
JavaScript Answers

How to fix ‘Access-Control-Allow-Origin’ issue when API call made from React isomorphic app?

To fix ‘Access-Control-Allow-Origin’ issue when API call made from React isomorphic app, we enable CORS on the back end.

For instance, we write

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

to enable CORS in a middleware by sending the Access-Control-Allow-Origin and Access-Control-Allow-Headers response headers.