Skip to content
This repository was archived by the owner on Aug 28, 2026. It is now read-only.

Repository files navigation

⚠️ DEPRECATED — moved to yingyeothon/tslib

This repository is archived and no longer maintained. Its packages now live in the tslib monorepo and are published from there as v2.0.0+ with a redesigned API (see each package's README there for migration notes).

Package here (last release from this repo) Successor in tslib
@yingyeothon/naive-socket @yingyeothon/naive-socket

Versions published from this repository stay on npm but are marked deprecated.

Naive Socket

This is a very lightweight library to communicate with the opposite using net.Socket.

Rationale

I'm a Serverless programmer and I want to reduce a deployment package size as possible as I can. There are lots of many libraries to do anything in this world but because of this they have the big codebase sometimes. For example, ioredis is the perfect library to use Redis in NodeJS but it is very big to use in Serverless environment.

This library is a very naive wrapper of net.Socket so it doesn't have functions to use. This is proper to use only when there is no need for complex features while communicating with the opposite, for example, the case of only sending an one command to Redis and finished.

Example

Fire and forget

This is a simple example when we don't expect the boundary of message. It would return any message that returns from the server immediately. So please be careful this message can be truncated because this function can finish before a message fully reached.

import NaiveSocket from "@yingyeothon/naive-socket";

const redisNewline = `\r\n`;
const naiveSocket = new NaiveSocket({
  host: "localhost",
  port: 6379
});

export const ping = () =>
  naiveSocket.send({
    message: [`PING`, ``].join(redisNewline)
  });

Using Length

Or, we can wait by the length of expected response when we know the exact length of the message that we want to receive. It helps ensure the message boundary when we communicate multiple commands in this one connection.

export const ping = () =>
  naiveSocket.send({
    message: [`PING`, ``].join(redisNewline),
    fulfill: `+PONG`.length
  });

Using RegExp

Or, in some cases, RegExp is more useful to check the correct message. This is a simple example to communicate with Redis with 2 cases.

  1. Send a message via Redis queue.
  2. Retrieve a gameId by userId.
export const enqueueGameMessage = (gameId: string, message: any) =>
  naiveSocket.send({
    message: [
      `RPUSH "queue/${gameId}" "${JSON.stringify(JSON.stringify(message))}"`,
      ``
    ].join(redisNewline),
    timeoutMillis: 1000
  });

export const loadGameId = (userId: string) =>
  naiveSocket
    .send({
      message: [`GET "gameId/${userId}"`, ``].join(redisNewline),
      // When the pattern of gameId is UUID.
      fulfill: /^(\$[0-9]+\r\n(?:[0-9A-Za-z_\-]+)\r\n|\$-1\r\n)/,
      timeoutMillis: 1000
    })
    .then(response => response.match(/([0-9A-F\-]+)\r\n/)[1] || "");

timeoutMillis will help us to prevent infinitely waiting due to invalid RegExp.

Using TextMatch

If we want to receive more complex response, for example, like the response of SMEMBERS in Redis, we can use TextMatch for this.

import { withMatch } from "@yingyeothon/naive-socket/lib/match";

export const loadMembers = (membersKey: string) =>
  naiveSocket.send({
    message: [`SMEMBERS "${membersKey}"`, ``].join(redisNewline),
    /* This is the pattern of its result.
     * *COUNT\r\n
     * $LENGTH\r\n
     * SOMETHING-VALUE\r\n
     * ...
     */
    fulfill: withMatch(m => {
      let count = +m
        .capture("\r\n") // Read the first line,
        .values()[0]
        .slice(1); // And parse the count from "*COUNT".
      while (count-- > 0) {
        m.capture("\r\n") // Read a length of next line,
          .capture("\r\n"); // Read a value.
      }
      return m;
    }),
    timeoutMillis: 1000
  });

License

MIT

About

A naive TCP Socket library to send and receive with the opposite.

Resources

Stars

0 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages