Categories
JavaScript Answers

How to differentiate clients with webSocketServer in Node.js?

To differentiate clients with webSocketServer in Node.js, we canm use the sec-websocket-key header.

For instance, we write

wss.on("connection", (ws, req) => {
  ws.id = req.headers["sec-websocket-key"];

  //...
});

to listen to the connection event with on.

And we get the sec-websocket-key header with req.headers["sec-websocket-key"] in the event handler to get the client’s ID.

Categories
JavaScript Answers

How to write objects into file with Node.js?

To write objects into file with Node.js, we call the writeFileSync method.

For instance, we write

fs.writeFileSync("./data.json", JSON.stringify(obj, null, 2), "utf-8");

to call the writeFileSync method to write the stringified obj object to data.json.

We convert obj to a JSON string with JSON.stringify.

Categories
JavaScript Answers

How to get raw request body using Express with Node.js?

To get raw request body using Express with Node.js, we use the req.body property.

For instance, we write

const bodyParser = require("body-parser");
app.use(bodyParser.raw(options));

app.get(path, (req, res) => {
  console.log(req.body);
  //...
});

to call app.get to create a route handler for the path path.

Then we get the request body with req.body.

req.body is a buffer object.

We use the bodyParser.raw middleware to parse the request body into a buffer.

Categories
JavaScript Answers

How to fix missing write access in mac to the /usr/local/lib/node_modules folder on Mac?

To fix missing write access in mac to the /usr/local/lib/node_modules folder on Mac, we’ve to set the folder’s owner to the current user.

For instance, we run

sudo chown -R $USER ~/.npm
sudo chown -R $USER /usr/lib/node_modules
sudo chown -R $USER /usr/local/lib/node_modules

to run chown to set the owner of the ~/.npm, /usr/lib/node_modules and the /usr/local/lib/node_modules folders to the current user.

Categories
JavaScript Answers

How to find user by username LIKE value with Mongoose.js and JavaScript?

To find user by username LIKE value with Mongoose.js and JavaScript, we use the findOne method with a regex.

For instance, we write

const name = "Peter";
model.findOne({ name: new RegExp("^" + name + "$", "i") }, (err, doc) => {
  //...
});

to call findOne to find the document with field name like the 'Peter' by setting name to a regex with name in it.

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

We get result from doc in the callback.