Unix dgram, seqpacket, etc binding for Node.js.

Overview

node-unix-socket

npm_bandage github_ci_status

node-unix-socket allows you to use some nonblocking unix sockets that are currently not supported by Node.js native modules, including:

  • unix seqpacket(SOCK_SEQPACKET) sockets
  • unix datagram(SOCK_DGRAM) sockets
  • Using SO_REUSEPORT enabled TCP net.Server

node-unix-socket is a napi-rs based Node.js addons. This lib uses libuv inside Node.js so that it won't introduce any other asynchronous runtimes.

Tested Platforms & Node.js

Platform Node.js DgramSocket Seqpacket
x64 Linux 12 + LTS
x64 Darwin 12 + LTS
aarch64 Darwin 12 + LTS

Installation

npm i node-unix-socket

API Documents

API Documents

Seqpacket Sockets

SOCK_SEQPACKET sockets are like SOCK_DGRAM sockets and they will keep message boundaries.

Note that SOCK_SEQPACKET sockets don't work on MacOS.

Example

const { SeqpacketServer, SeqpacketSocket } = require('node-unix-socket');
const os = require('os');
const path = require('path');
const fs = require('fs');

const bindPath = path.resolve(os.tmpdir(), './my_seqpacket.sock');

try {
  fs.unlinkSync(bindPath);
} catch (e) {}

const server = new SeqpacketServer();
server.listen(bindPath);
server.on('connection', (socket) => {
  socket.on('data', (buf) => {
    console.log('received', buf.toString());
  });
});

const client = new SeqpacketSocket();
client.connect(bindPath, () => {
  const data = ['hello, ', 'w', 'o', 'r', 'l', 'd'];

  for (const str of data) {
    client.write(Buffer.from(str));
  }
  client.end();
});

Dgram Sockets

Example

const { DgramSocket } = require('node-unix-socket');
const os = require('os');
const path = require('path');
const fs = require('fs');

const path1 = path.resolve(os.tmpdir(), './my_dgram_1.sock');
const path2 = path.resolve(os.tmpdir(), './my_dgram_2.sock');

try {
  fs.unlinkSync(path1);
  fs.unlinkSync(path2);
} catch (err) {}

const socket1 = new DgramSocket();
const socket2 = new DgramSocket();

socket1.bind(path1);
socket2.bind(path2);

socket2.on('data', (data, remoteAddr) => {
  console.log(`socket2 received: ${data.toString()}`);
  // echo
  socket2.sendTo(data, 0, data.length, remoteAddr);
});

socket1.on('data', (data) => {
  console.log(`socket1 received: ${data.toString()}`);
});

setInterval(() => {
  const buf = Buffer.from('hello');
  socket1.sendTo(buf, 0, buf.length, path2);
}, 1000);

SO_REUSEPORT enabled TCP net.Server

The cluster module share server ports by accepting new connections in the primary process and distributing them to worker processes.

With SO_REUSEPORT, sockets will be distributed by kernel instead, and which should be more performant especially for scenario of having a lot of short-lived connections.

For example, the arrow in the image below shows cpu usage of a PM2 primary process which we found in our environment.

cpu_usage

Note that SO_REUSEPORT might behave much differently across operating systems. See this post for more information.

Example

const { createReuseportFd } = require('node-unix-socket');
const { Server, Socket } = require('net');

const port = 8080;
const host = '0.0.0.0';

// create multple servers listening to a same host, port.
for (let i = 0; i < 2; i += 1) {
  const fd = createReuseportFd(port, host);
  const server = new Server((socket) => {
    socket.on('data', (buf) => {
      console.log(`server ${i} received:`, buf);
      // echo
      socket.write(buf);
    });
  });

  server.listen(
    {
      fd,
    },
    () => {
      console.log(`server ${i} is listening on ${port}`);
    }
  );
}

setInterval(() => {
  const client = new Socket();
  client.on('data', (buf) => {
    console.log('client received:', buf);
    client.destroy();
  });
  client.connect(port, host, () => {
    client.write(Buffer.from('hello'));
  });
}, 1000);

CONTRIBUTING

CONTRIBUTING.md

LICENSE

MIT

You might also like...

Inter Process Communication Module for node supporting Unix sockets, TCP, TLS, and UDP. Giving lightning speed on Linux, Mac, and Windows. Neural Networking in Node.JS

Inter Process Communication Module for node supporting Unix sockets, TCP, TLS, and UDP. Giving lightning speed on Linux, Mac, and Windows. Neural Networking in Node.JS

Inter Process Communication Module for node supporting Unix sockets, TCP, TLS, and UDP. Giving lightning speed on Linux, Mac, and Windows. Neural Networking in Node.JS

Dec 9, 2022

rtail(1) - Terminal output to the browser in seconds, using UNIX pipes.

rtail(1) - Terminal output to the browser in seconds, using UNIX pipes.

rtail(1) Terminal output to the browser in seconds, using UNIX pipes. rtail is a command line utility that grabs every line in stdin and broadcasts it

Jan 6, 2023

Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

May 18, 2022

Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

May 3, 2022

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

A Node.js binding to webview

webview-nodejs English | 中文(简体) A Node.js binding to webview, a tiny cross-platform webview library to build modern cross-platform desktop GUIs using

Dec 13, 2022

Node.js implementation binding for the RWKV.cpp module

RWKV.cpp NodeJS bindings Arguably the easiest way to get RWKV.cpp running on node.js. # Install globally npm install -g rwkv-cpp-node # This will sta

May 10, 2023

we learn the whole concept of JS including Basics like Object, Functions, Array etc. And Advance JS - Understanding DOMs, JQuery, Ajax, Prototypes etc.

JavaScript-for-Complete-Web Development. we learn the whole concept of JS including Basics like Object, Functions, Array etc. And Advance JS - Underst

Jul 22, 2022

A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.

KeyboardJS KeyboardJS is a library for use in the browser (node.js compatible). It Allows developers to easily setup key bindings. Use key combos to s

Dec 30, 2022

Lightweight and powerful data binding.

Rivets.js Rivets.js is a lightweight data binding and templating system that facilitates building data-driven views. It is agnostic about every aspect

Dec 28, 2022

A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.

KeyboardJS KeyboardJS is a library for use in the browser (node.js compatible). It Allows developers to easily setup key bindings. Use key combos to s

Dec 30, 2022

A data-binding function for the DOM.

Alert: this library is now deprecated. s2 is its successor. It implements what simulacra does in a better way (using Proxy), and more. Simulacra.js Si

Nov 18, 2022

A tiny, SSR-safe directive for binding random data to an element.

1️⃣ vue-bind-once A tiny, SSR-safe directive for binding random data to an element. A tiny, SSR-safe directive for binding random data to an element.

Jan 8, 2023

An easy peasy UI binding library.

Peasy UI This is the repository for Peasy UI, a small-ish and relatively easy to use UI binding library. Introduction Peasy UI provides uncomplicated

Nov 8, 2022

Necktie – a simple DOM binding tool

👔 Necktie – a simple DOM binding tool Necktie is a library that binds your logic to the Document Object Model elements in an easy way. It has only ~3

Oct 7, 2022

Build Schema.org graphs for JavaScript Runtimes (Browser, Node, etc). Improve your sites SEO with quick and easy Rich Results.

schema-org-graph-js The quickest and easiest way to build Schema.org graphs for JavaScript Runtimes (Browser, Node, etc). Status: 🔨 In Development Pl

Dec 21, 2022

Template to start developing a REST API with Node.js (Express), TypeScript, DDD, etc. 🔰🦸

Template to start developing a REST API with Node.js (Express), TypeScript, DDD, etc. 🔰🦸

Typescript DDD Boilerplate Plantilla para una API con Typescript basada en arquitectura DDD. En qué consiste este proyecto Este proyecto es un punto d

Nov 26, 2022

Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.

You (Might) Don't Need jQuery Frontend environments evolve rapidly nowadays and modern browsers have already implemented a great deal of DOM/BOM APIs

Dec 24, 2022

Selectize is the hybrid of a textbox and select box. It's jQuery based and it has autocomplete and native-feeling keyboard navigation; useful for tagging, contact lists, etc.

selectize.js → Selectize is looking for new members on the maintenance team! Selectize is an extensible jQuery-based custom select UI control. It's

Dec 31, 2022
Comments
  • Typescript is broken

    Typescript is broken

    node_modules/node-unix-socket/js/seqpacket.ts:237:26 - error TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
      Type 'undefined' is not assignable to type 'number'.
    
    237     this.wrap.write(buf, offset, length, cb);
                                 ~~~~~~
    
    opened by Shonke 2
Releases(v0.2.4)
A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)

WebSocket Client & Server Implementation for Node Overview This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and

Brian McKelvey 3.6k Dec 30, 2022
WebSocket emulation - Node.js server

SockJS-node SockJS for enterprise Available as part of the Tidelift Subscription. The maintainers of SockJS and thousands of other packages are workin

SockJS 2.1k Dec 29, 2022
Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js

ws: a Node.js WebSocket library ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation. Passes the quit

WebSockets 19.2k Jan 4, 2023
μWebSockets for Node.js back-ends :metal:

Simple, secure[1] & standards compliant[2] web server for the most demanding[3] of applications. Read more... A note on NPM drama ⚡ Simple performance

uNetworking AB 5.7k Jan 8, 2023
JSON-RPC 2.0 implementation over WebSockets for Node.js and JavaScript/TypeScript

WebSockets for Node.js and JavaScript/TypeScript with JSON RPC 2.0 support on top. About The rpc-websockets library enables developers to easily imple

Elpheria 482 Dec 21, 2022
ONG-Node JS

Server Base - Proyecto ONG Envinroment setup Create database Copy .env.example to .env and fill with database credentials.

Alkemy 2 Dec 30, 2021
Sse-example - SSE (server-sent events) example using Node.js

sse-example SSE (server-sent events) example using Node.js SSE is a easy way to commutate with the client side in a single direction. it has loss cost

Jack 2 Mar 11, 2022
Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js

CHAT-APP-WEBSOCKET Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js Obs o intuito deste projeto não é o fronten

Vinicius dos Santos Rodrigues 4 Jul 14, 2022
Node.js library to receive live stream chat events like comments and gifts in realtime from TikTok LIVE.

TikTok-Live-Connector A Node.js library to receive live stream events such as comments and gifts in realtime from TikTok LIVE by connecting to TikTok'

David 399 Jan 4, 2023
This Repository implements an Authenticated Websocket Server built in Node Js along ws library.

websockets-authentication-server This Repository implements an Authenticated Websocket Server built in Node Js along ws library. Features Authenticate

M.Abdullah Ch 7 May 5, 2023