Categories
JavaScript Answers

How to create rooms in Node Socket.io?

To create rooms in Node Socket.io, we call in and join.

For instance, on client side, we write

const socket = io.connect();
socket.emit("create", "room1");

to call emit to emit the create event with the room name.

On server side, we write

io.sockets.on("connection", (socket) => {
  socket.on("create", (room) => {
    socket.join(room);
  });
});

to call on to listen for the create event and call join to create the room.

Then we can send messages to the room with

io.sockets.in(room).emit("event", data);

by call in with the room name.

Categories
JavaScript Answers

How to fix Error: EACCES: permission denied when trying to install ESLint using npm?

To fix Error: EACCES: permission denied when trying to install ESLint using npm, we set a few options.

For instance, we run

sudo npm install -g eslint --unsafe-perm=true --allow-root

to install eslint with npm install with --unsafe-perm=true and --allow-root to install as root and run with root permissions.

Categories
JavaScript Answers

How to add Node Express Passport error handling?

To add Node Express Passport error handling, we use the middleware returned by passport.authenticate.

For instance, we write

app.post(
  "/login",
  passport.authenticate("local", {
    successRedirect: "/loggedin",
    failureRedirect: "/login",
    failureFlash: true,
  })
);

to call passport.authenticate to return the authentication middleware.

We use that as the argument of post to make it use Passport authentication.

We set the successRedirect and failureRedirect properties to set the redirect destination in both cases.

Categories
JavaScript Answers

How to get all the values that contains part of a string using Node Mongoose find?

To get all the values that contains part of a string using Node Mongoose find, we can search with a regex.

For instance, we write

Books.find({ authors: /Alex/i }, (err, docs) => {});

to call find with an object that has authors set to the regex with the pattern we’re looking for.

And we get the results from the docs array.

We use the i flag to search in a case insensitive manner.

Categories
JavaScript Answers

How to get HTTP headers with Node.js?

To get HTTP headers with Node.js, we use the headers property.

For instance, we write

const http = require("http");
const options = { method: "HEAD", host: "example.com", port: 80, path: "/" };
const req = http.request(options, (res) => {
  console.log(JSON.stringify(res.headers));
});
req.end();

to call http.request with the options to make a get request.

And we get the response headers with res.headers in the callback.