When attempting to use the node.js REPL over a socket, the connection will unexpectedly terminate if the user presses CTRL + C

As I attempt to utilize REPL over a socket in a manner similar to a telnet connection, I have encountered an issue whereby pressing CTRL + C or CTRL + D, or encountering an error result in the socket connection becoming unresponsive.

The code written in node.js is as follows:

var net = require("net");
var connections = 0;

// Establishing Socket port 5001
net.createServer(function (socket) {
  connections += 1;
  var server = require("repl").start(
      'session:' + connections + ' > ', 
      socket
  );
  server.rli.on('exit', function() {
    socket.end();
  });
}).listen(5001);

// Console
var server = require("repl").start('session:' + (++connections) + ' > ', null);

To implement this, I run the following command in another terminal:

telnet localhost 5001

However, I am facing difficulties. What could be causing this behavior?

Answer №1

It could be a Linux-related issue.

I decided to experiment with a Telnet server example using Node.js. When testing it on Windows, each key press triggered the receiveData function, but on Linux, this did not happen. In Linux, the processing seemed to occur line by line rather than character by character.

Below is the code snippet I tested:

var net = require('net');
var sockets = [];

/*
 * Removes carriage return and newline characters from input
 */
function cleanInput(data) {
    return data.toString().replace(/(\r\n|\n|\r)/gm,"");
}

/*
 * Executed when data is received from a socket
 */
function receiveData(socket, data) {
    var cleanData = cleanInput(data);
    if(cleanData === "@quit") {
        socket.end('Goodbye!\n');
    }
    else {
        for(var i = 0; i<sockets.length; i++) {
            if (sockets[i] !== socket) {
                sockets[i].write(data);
            }
        }
    }
    socket.write('Data: ' + data);
}

/*
 * Executed when a socket connection ends
 */
function closeSocket(socket) {
    var i = sockets.indexOf(socket);
    if (i != -1) {
        sockets.splice(i, 1);
    }
}

/*
 * Callback method executed when a new TCP socket connection is established
 */
function newSocket(socket) {
    sockets.push(socket);
    socket.write('Welcome to the Telnet server!\n');
    socket.on('data', function(data) {
        receiveData(socket, data);
    })
    socket.on('end', function() {
        closeSocket(socket);
    })
}

// Create a new server instance and specify a callback for handling connections
var server = net.createServer(newSocket);

// Start listening on port 8888
server.listen(8888);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Encountering issues with node-gyp rebuild error during installation of node-memwatch on CentOS 6

While attempting to install memwatch using "npm install memwatch", I encountered the following error: The server is running CentOS6 with Python 2.6.6 installed. [email protected] install /home/[[username]]/public_html/sockets/node_modules/memwatch ...

Issue finding a route based on dates

Hey everyone, I'm working on a feature where I need to fetch tasks made by a user within a specific date range provided by the user. However, I am facing some issues with getting the date and routing it. Here is the URL format that I am trying to work ...

Uploading PDFs using Node.js

Hello, I am trying to upload a PDF file in Node.js. I attempted to use the Sharp package, but unfortunately, it did not work as expected. await sharp(req.files.cover[0].buffer) .resize(2000, 1333) .toFormat("jpeg") .jpeg({ quality: 90 }) .toFile(public/im ...

Steps for redirecting a user back to the previous page with passport-spotify

Currently, I am utilizing passport-spotify for authentication in my web application from this Github repository: https://github.com/jmperez/passport-spotify. However, I seem to be facing an issue with redirecting the user back to the previous page. I have ...

Successfully made AJAX call using nodeJS and express, data not being shown on display

I recently transitioned from a codeigniter framework to a nodejs with an express framework. Our previous codeigniter site heavily utilized JavaScript and made numerous AJAX calls since it was a single page application. As we delve into node and express, I ...

Steps to modify the Angular Universal entry file to app.js and relocate it to the root directory of the app

Currently, I have an Angular Universal SSR application running on node with the latest versions of Angular and Universal as of 21/01/2021. My hosting provider allows me to host my nodejs apps on a shared cPanel, but they only accept the entry file named a ...

Cors policy error encountered in Node.js application and React application

I have developed an application using Node.js and React. I am currently hosting the server side on node.kutiza.com and the client side on finanu.kutiza.com through Namecheap. However, when I try to make a request to node.kutiza.com, I encounter an error me ...

Attempting to understand the findings of the npm audit

Context Upon running the npm audit command on an old ReactJS project that we recently revisited after a year, a summary of 356 vulnerabilities was obtained (321 low, 20 moderate, 14 high, 1 critical) across 11345 scanned packages. Executing npm audit fix ...

I keep encountering a TokenError while trying to authenticate using OAuth2Strategy with Passport in my Node Express application. What could be causing

Having some trouble with the OAuth2Strategy for Passport JS and Express (4). After being redirected to log in, I am taken back to my callback URL where I encounter this error message: TokenError: Invalid client or client credentials at OAuth2Strategy ...

Testing an Express route in Node.js using a mocked module

I am just starting out with NodeJS and I could use some assistance in testing a basic API that I have developed using Express. Here is the route in my API: router.get('/execute', function(req, res, next) { console.log("Execute Request Query: %s ...

Tips for setting up listeners across multiple modules using socket.io

Last year, I created a multiplayer game using node.js and socket.io. Now, as part of my efforts to enhance the game, I am working on breaking down the code into modules. Currently, I am utilizing expressjs 4.4 along with socket.io 1.0. One challenge I enco ...

Different ways to activate the system bell in Node.js

Currently, I have a custom nodejs script running for an extended period and I'm seeking a way to receive a notification once the script finishes its execution. Is there a method in nodejs that can be used to activate the "System Bell" alert? ...

Tips for storing an array of objects in MongoDB with Mongoose

Here are some code snippets that involve objects: var s; var tab = []; var myarray= []; for(var i=0;i<=tab.length-1;i++){ s= "{\"id\":\"" + tab[i][0] + "\",\"ts\":\"" + tab[i][1] + "\",\"lat&bs ...

Exploring the Integration of Node Modules with React

I am still learning about Node and I'm struggling to integrate an NPM package with my React project running on Node. Currently, I have a React component that successfully uploads a zip file through Node server scripts. Now, I am working on the next s ...

Storing data in a database in Node.js without the use of forms involves passing values through API endpoints

Looking for guidance on developing a simple car rental management website utilizing nodejs,express and mongodb. I am seeking assistance on how to pass a value, save it in the database and showcase it on the subsequent page without relying on a form. For ...

Transfer the user object to a designated route in Express

Is there a way to pass the user object to a specific route before redirecting to that route? I have attempted using the solution mentioned here, but unfortunately, it is returning undefined. The scenario involves redirecting the user from the signup route ...

What is the principalId/type for IBM Bluemix Mobile Client Access when using Loopback ACLs?

I am working on enhancing the security of my loopback app Models to ensure that only users authenticated through Mobile Client Access (bluemix) can perform a POST operation to a specific model, while the rest of the models are accessible to authenticated u ...

What is the best way to perform a cascade delete in a one-to-one relationship?

One issue I encountered is with the deletion of users and their associated employees. How can I ensure that when a user is deleted, the corresponding employee is also removed, and vice versa? Below is my User model: const mongoose = require('mongoose ...

Node.js encountered an abrupt conclusion in the JSON input that was not anticipated

Upon receiving Json data as post data in my node.js server, I encountered an issue with parsing the string. Here is a snippet of my node.js server code: res.header("Access-Control-Allow-Origin", "*"); req.on('data',function(data) { var ...

The Electron BrowserWindow turns dark post execution of the .show() method

Revision: After some tinkering, I discovered that the issue was related to the order in which I created the windows. Previously, my code looked like this: app.whenReady().then(() => { createWindow(); spawnLoadingBlockWindow(); spawnGenerati ...