Categories
JavaScript Answers

How to get the client’s IP address in socket.io and JavaScript?

To get the client’s IP address in socket.io and JavaScript, we use the handshake.address property.

For instance, we write

const io = require("socket.io").listen(server);

io.sockets.on("connection", (socket) => {
  const address = socket.handshake.address;
  console.log(address.address, address.port);
});

to listen for the connection event with on.

We get the client address from socket.handshake.address.

And we get the IP address and port from the returned address.

Categories
JavaScript Answers

How to promisify Node’s child_process.exec and child_process.execFile functions with Node.js Bluebird?

To promisify Node’s child_process.exec and child_process.execFile functions with Node.js Bluebird, we use the util.promisfy method.

For instance, we write

const util = require("util");
const exec = util.promisify(require("child_process").exec);

const run = async () => {
  try {
    const { stdout, stderr } = await exec("ls");
    console.log("stdout:", stdout);
    console.log("stderr:", stderr);
  } catch (e) {
    console.error(e);
  }
};

to call util.promisify with the child_process module’s exec method to convert it to return a promise.

Then we define the run function that calls exec to run a command.

It returns a promise, so we await to get an object with the stdout and stderr outputs.

This works with Node.js 10 or later.

Categories
JavaScript Answers

How to fix nodemon command is not recognized in terminal for Node.js server?

To fix nodemon command is not recognized in terminal for Node.js server, we put nodemon in a script in package.json.

For instance, in package.json, we write something like

{
  //....
  "scripts": {
    "server": "nodemon server.js"
  }
  //....
}

to run server.js with nodemon.

Then we run

npm run server

to run the script.

We install nodemon with

npm i nodemon
Categories
JavaScript Answers

How to install the babel-polyfill library with JavaScript?

To install the babel-polyfill library with JavaScript, we run npm install.

For instance, we run

npm install --save-dev  @babel/core @babel/cli @babel/preset-env
npm install --save @babel/polyfill

to install the @babel/polyfill package along with the other required Babel packages.

Categories
JavaScript Answers

How to properly export an ES6 class in Node.js?

To properly export an ES6 class in Node.js, we set the class as the value of module.exports.

For instance, in person.js, we write

"use strict";

module.exports = class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  display() {
    console.log(this.firstName, this.lastName);
  }
};

to export the Person class.

Then we write

const Person = require("./person.js");

const someone = new Person("First name", "Last name");
someone.display();

to require the person.js module and then create a Person instance.