Categories
JavaScript Answers

How to fix Socket.io and Node.js Cross-Origin request blocked?

To fix Socket.io and Node.js Cross-Origin request blocked, we add a cors option into the server.

For instance, we write

const io = require("socket.io")(server, {
  cors: {
    origin: "*",
  },
});

to set the cors.origin property to allow connection from all origins.

Categories
JavaScript Answers

How to print a list of all installed Node.js modules?

To print a list of all installed Node.js modules, we use the list option.

For instance, we run

npm -g list

to list all the globally installed packages.

We run

npm list

to list the packages installed in the project folder.

Categories
JavaScript Answers

How to force strict mode in Node.js?

To force strict mode in Node.js, we use the 'use strict' directive.

For instance, we write

"use strict";

to our JavaScript files to enable strict mode.

Categories
JavaScript Answers

How to Create and Use Enum in Mongoose and JavaScript?

To create and use enum in Mongoose and JavaScript, we can add an enum field into the schema.

For instance, we write

const userSchema = new mongoose.Schema({
  userType: {
    type: String,
    enum: ["user", "admin"],
    default: "user",
  },
});

to create a schema with Schema.

We call it with an object that has the enum property with the possible values for the enum to create the userType enum field that is a string that can either be 'user' or 'admin'.

Categories
JavaScript Answers

How to execute an external program from within Node.js?

To execute an external program from within Node.js, we use the exec function.

For instance, we write

const exec = require("child_process").exec;
exec("pwd", (error, stdout, stderr) => {
  // result
});

to call exec with the command we want to run and the callback that’s called when the command is finished running.

We get its output from stdout.

And we get the command’s error output from stderr.