Splitting data in NodeJS sockets

Whenever I encounter the need to divide data, my standard practice involves converting it into a string format.
Here's an example of how I handle data in my function:

  socket.on('data', function (data) {
    var str = data.toString().split("|");
    switch(str[0]){
        case "setUser":
        setUser(str[1], socket);
        break;
        case "joinChannel":
        joinChannel(str[1], socket);
        break;
    }

  });

During communication between my AS3 client and NodeJS server, sending data like "setUser|Name" followed by "joinChannel|main" results in NodeJS reading them as a single data packet. My query is regarding how to separate these into two distinct data packets.

Answer №1

To efficiently handle incoming data, it is recommended to buffer all the data together and then parse it as a single string. Alternatively, if parsing needs to be done as data comes in, splitting can be implemented in the data callback while keeping track of any partial commands that need to be processed along with the next chunk received.

var data = '';
socket.setEncoding('utf8');
socket.on('data', function(chunk) {
  data += chunk;
});
socket.on('end', function() {

  var lines = data.split('\n');
  lines.forEach(function(line) {
    var parts = line.split('|');
    switch (parts[0]) {
      case 'setUser':
        setUser(str[1], socket);
        break;
      case 'joinChannel':
        joinChannel(str[1], socket);
        break;
    }
  });
});

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

Issues with non-functional plugins that utilize AJAX functionality

I am encountering an issue with my code that includes an ajax script for deleting a record, along with an animation during the deletion process. However, when I try to integrate the ajax script with plugins for confirmation, it seems to not be working prop ...

Exploring External Functions in Angular Beyond the Library

Transitioning from standard JavaScript to Angular has been a bit challenging for me, especially when working with the Google Places library (or any other asynchronous callback). Here is the code snippet: var sparkApp = angular.module('sparkApp' ...

Displaying the votes through an advanced system called Ajax voting system

I've encountered a challenge while using an ajax voting system in my project. The issue is that I'm utilizing a div with an id to showcase the votes, but whenever someone clicks on vote up or down in any of the posts (which are generated through ...

Are there any solutions for the malfunctioning v8 date parser?

The V8 Date parsing functionality is not functioning properly: > new Date('asd qw 101') Sat Jan 01 101 00:00:00 GMT+0100 (CET) I have attempted to use a delicate regular expression like the following: \d{1,2} (jan|feb|mar|may|jun|jul|a ...

Clear v-model without changing its associated values

I'm facing an issue with my <input> fields, which look like this: <input type="text" v-model=user.name" /> <input type="text" v-model="user.phone" /> <button @click="add">add user</button> Whenever the add user button i ...

What is the best way to show information entered into a textbox on a different webpage?

Looking for advice on how to collect data in a text box and display it on another page? I have included HTML code for both the announcement page (where the data is entered) and the archive page (where the data should be shown). Could someone guide me on ...

vue-loader: The specified module could not be located

I'm stuck trying to solve the issue with the module not found error. This module is relative and cannot be located: ./graphics/logo.svg in ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIden ...

select items using a dropdown menu in an Angular application

Let me describe a scenario where I am facing an issue. I have created an HTML table with certain elements and a drop-down list Click here for image illustration When the user selects in, only records with type in should be displayed Another image refere ...

Bizarre actions with jQuery append in Internet Explorer 8

Issue with adding elements to a div in IE8: The element is not added until the button is clicked twice, resulting in two new elements being added at once. Here's the code snippet in question: $(options.addButton).click(function(event) { var proto ...

What is the process of incorporating an Auto-increment field for previously added records in MongoDB by utilizing the Mongoose-sequence

I successfully implemented auto-increment functionality for my MongoDB collection. Now, I am facing a challenge in adding this feature to the existing records within the database. Specifically, I am aiming to incorporate an auto-incrementing project_id fi ...

Using JavaScript, adding an element to an array results in the array returning a value of 1

When I try to push a string into an array and then return the array, I am getting unexpected result of "1". Upon closer inspection, it seems that the array is being successfully created but before returning it, only "1" is being returned. Here is the snip ...

Steps for ensuring a promise is fulfilled in Node.js and Firebase

I've been struggling with this issue for quite some time now and can't seem to figure it out. g_globalList.once("value").then(function(tickList){ var multiPaths = []; tickList.forEach(function(ticker){ ticker.val().forEach(fu ...

What is the best way to modify a variable in a nested element using ng-click in the parent element?

Review this code snippet: <section class="page-section about-us" scroll-bookmark="about-us" ng-click="activeSection=true" ng-init="activeSection=false"> <div class="page-content sub-content active-section">{{activeSection}} < ...

I can't seem to figure out which of these 4 statements is free of syntax errors

Can you identify which code block does not contain a syntax error? Out of the 4 options below, one of them is free from any syntax mistakes. alert("hello "+3+" times); alert("hello "+3 times); alert("hello +3+ times"); alert("hel ...

Avoid Scrolling within an iFrame in HTML with the Use of #

I have a menu loading in an iframe with links using # like http://<location>/page.html#part1. When I click inside the iframe, the entire page outside of the iframe scrolls to the location of #. How can I stop this from happening? I only want the me ...

Tips for avoiding a form reload on onSubmit during unit testing with jasmine

I'm currently working on a unit test to ensure that a user can't submit a form until all fields have been filled out. The test itself is functioning correctly and passes, but the problem arises when the default behavior of form submission causes ...

Refreshing an external file in Node.js at regular intervals

Seeking guidance on loading external files in node. I'm currently working with an external JSON file that houses some configuration settings, and this file gets updated by an outside process every 10 minutes. How can I automate the reloading of this ...

What are the steps to rectify the issue of displaying data accurately on

I am working on my ReactJS project and using devextreme to create a unique circular gauge. However, I'm facing an issue where certain values are not being displayed correctly. For instance, instead of showing the value 5011480286.78, it is displaying ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

Collaborative spreadsheet feature within a browser-based software platform

I am using an Angular-based SPA for my web application. My goal is to be able to open an Excel file within the application itself. Currently, I have a menu button or link that is linked to a specific path, for example //192.168.10.10/sharedExcels/myExcel. ...