Categories
Node.js Tips

Node.js Tips — REPL Tips, Socket.io Connections, and Event Listeners

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Remove Event Listeners in Node.js Event Emitter

We can remove listeners with Node event emitter by using the removeListener method.

For instance, we can write:

const events = require('events');
const EventEmitter = events.EventEmitter;
const rr = new EventEmitter();
const refreshHandler = () => {
  console.log('refresh');
}
rr.on("refresh", refreshHandler);
rr.removeListener("refresh", refreshHandler);

We created our EventEmitter instance.

Then we attach the refreshHandler event listener to the refresh event.

If we don’t need to listen to the refresh event anymore, then we can call removeListener to clear the event listener from memory.

We pass in the event name as the first argument of removeListener .

And the 2nd is the event handler we want to remove.

The Meaning of the “_” (underscore) Symbol in Node.js REPL

The _ symbol returns the result of the last logged expression in the REPL,

For instance, if we typed:

> 2 * 3
6

Then _ returns 6:

> _
6

Access Variable from an exec Callback Function in Node.js

exec takes a callback function with the result of running a shell command.

For instance, we can write:

const execChild = (callback) => {
  const child = exec(cmd, (error, stdout, stderr) => {
    callback(stdout);
  });
}

We get the stdout from the callback, which has the results of our cmd command.

Then we call callback to get the result outside of the exec callback.

We’ve to do this because exec is async, so we won’t know when we’ll get the result.

Now we can use the execChild function by writing:

execChild((result) => console.log(result));

The stdout that we passed into the callback would be the result .

Socket.io —Listen for Connection Event

We can listen for connections on server side.

And we then make connections from the client-side.

On our server-side code, we write:

const io = require('socket.io').listen(8001);
io.sockets.on('connection', (socket) => {
  console.log('user connected');
});

to listen to the connection event, which will be emitted from the client if we call io.connect .

Then in our client-side code, we write:

const socket = io.connect('http://localhost:8001');

to connect to the server we created.

Get a Full File Path in Node.js

We can get the __dirname to get the full path of the current directory.

Then w can write:

const path = require("path");
const fileName = "file.txt";
const fullPath = path.join(__dirname, "/uploads/", fileName);

We use path.join to join all the path segments together in a platform-agnostic way.

Also, we can use the path.resolve method to return the full path to a file.

For instance, we can write:

const path = require("path");
const fullPath = path.resolve("./uploads/file.csv");

We call resolve with the relative path to get the full path of the file.

Get Client’s IP with Express

If we’re writing an Express app, then we can use req.ip to get the client’s IP address.

We can also get the value of the x-forward-for header by writing:

req.headers['x-forwarded-for']

to get the header’s value, which has the IP address.

We can also check req.connection.remoteAddress to do the same thing.

Connect to Socket.Io Server with Specific Path and Namespace

We can connect to a socket.io server with a specific path and namespace by using the of method and the path property.

For instance, we can write:

const io = require('socket.io')(http, {
  path: '/foo/bar'
});

io
  .of('/namespace')
  .on('connection', (socket) => {
    socket.on('message', (data) => {
      io.of('namespace').emit('message', data);
    });
  });

We pass in the http server instance to the socket.io function.

The 2nd argument lets us specify the path with the path property.

Then in the io.of method, we specify the namespace.

The on method lets us watch for connections from clients.

We can listen to events from the client with socket.on .

The first argument is the event name.

The 2nd is a callback that has the data emitted with the event.

Conclusion

We can use removeListener to clear event listeners.

We can connect to a specific path and namespace with socket.io.

It’s easy to get various file and network information with Node.

We can use _ to get the last result that’s returned in the Node REPL.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *