create-local-domain-socket

1.0.2 • Public • Published

create-local-domain-socket

Build Status Build status Coverage Status npm version License

A helper function to create cross-platform local domain sockets (UNIX domain sockets on UNIX, and named pipes polyfill on Windows).

Usage

createLocalDomainSocket

import createLocalDomainSocket from 'create-local-domain-socket';
import http from 'http';
 
/* create a whatever you want server */
const server = http.createServer((req, res) => {
  const body = http.STATUS_CODES[426];
  res.writeHead(426, {
    'Content-Length': body.length,
    'Content-Type': 'text/plain'
  });
  res.end(body);
});
 
createLocalDomainSocket(server, '/tmp/test.sock', (err) => {
  if (err) { console.error(err); }
  else { console.log('socket server started'); }
});

If you prefer using promise:

const server = http.createServer();
createLocalDomainSocket(server, '/tmp/test.sock')
  .then(() => console.log('socket server started'))
  .catch((err) => console.error(err))
;

Arguments

  1. server <Object>: A server object. Should include a .listen() and .on('error') methods to start and catch errors
  2. path <String>: Local domain path
  3. callback <Function> (Optional): A callback function. The first argument is an Error object if listen failed. If callback is undefined, it will return a promise

ensureLocalDomainPath

A tiny helper function to ensure local domain path. On Windows, it will convert to named pipe path instead of local domain path.

Example on Windows

import { ensureLocalDomainPath } from 'create-local-domain-socket';
 
const path = ensureLocalDomainPath('/test');
console.log(path); /* "\\\\.\\pipe\\test" */

Installation

npm install --save create-local-domain-socket

Example to integrate with ws

import WebSocket from 'ws';
import createLocalDomainSocket from 'createLocalDomainSocket';
import http from 'http';
 
const server = http.createServer((req, res) => {
  const body = http.STATUS_CODES[426];
  res.writeHead(426, {
    'Content-Length': body.length,
    'Content-Type': 'text/plain'
  });
  res.end(body);
});
 
createLocalDomainSocket(server, path, (err) => {
  if (err) { done.fail(err); }
  else {
    const wss = new WebSocket.Server({ server });
    const ws = new WebSocket(`ws+unix://${path}`);
    ws.on('message', (message) => {
      /* do sth... */
    });
    wss.on('connection', (client) => {
      client.send('sth');
    });
  }
});

License

MIT

Package Sidebar

Install

npm i create-local-domain-socket

Weekly Downloads

16

Version

1.0.2

License

MIT

Unpacked Size

8.36 kB

Total Files

4

Last publish

Collaborators

  • cap32