Categories
JavaScript Answers

How to fix npm install hangs on loadIdealTree:loadAllDepsIntoIdealTree: sill install loadIdealTree?

To fix npm install hangs on loadIdealTree:loadAllDepsIntoIdealTree: sill install loadIdealTree, we remove the package.json file.

To fix this, we remove the package.json file and then run

npm install

to install all packages again.

Categories
JavaScript Answers

How to broadcast messages on a namespace with Node socket.io?

To broadcast messages on a namespace with Node socket.io, we call broadcast.emit.

For instance, we write

chat.on("connection", (socket) => {
  socket.on("message", (msg) => {
    socket.emit(msg);
    socket.broadcast.emit(msg);
  });
});

to call broadcast.emit to broadcast the msg string to all clients.

Categories
JavaScript Answers

How to use .env variables in main app module file for database connection with Node Nest.js?

To use .env variables in main app module file for database connection with Node Nest.js, we can use the dotenv package.

To install it, we run

npm install dotenv

Then we add the scripts with

{
  "scripts": {
    //...
    "start:local": "NODE_ENV=local npm run start",
    "start:dev": "NODE_ENV=dev npm run start"
  }
}

to set the NODE_ENV environment variable before starting the app.

Then we load the .env file for the environment with

require("dotenv").config({ path: `../${process.env.NODE_ENV}.env` });

We get the NODE_ENV environment variable with process.env.NODE_ENV.

And we call config to load the .env file at the path.

Categories
JavaScript Answers

How to use Node Nest.js Logging service?

To use Node Nest.js Logging service, we use the Logger constructor.

For instance, we write

@Controller()
export class AppController {
  private readonly logger = new Logger(AppController.name);

  @Get()
  async get() {
    this.logger.log("Getting stuff");
  }
}

to create a Logger object with the name of the controller.

Then we call logger.log to log some text.

Categories
JavaScript Answers

How to fix Node.js connect only working on localhost?

To fix Node.js connect only working on localhost, we call listen with '0.0.0.0'.

For instance,. we write

const app = connect().use(connect.static("public")).listen(3000, "0.0.0.0");

to call listen with "0.0.0.0" to listen for requests from all IP addresses.