create-local-domain-socket
v1.0.2
Published
A helper function to create cross-platform local domain sockets
Downloads
15
Maintainers
Readme
create-local-domain-socket
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
server
<Object>: A server object. Should include a.listen()
and.on('error')
methods to start and catch errorspath
<String>: Local domain pathcallback
<Function> (Optional): A callback function. The first argument is anError
object if listen failed. Ifcallback
isundefined
, 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