create writer synchronously, win detection fix

This commit is contained in:
AJ ONeal 2017-04-28 12:24:39 -06:00
parent 00fd61add0
commit fea769a271
2 changed files with 11 additions and 9 deletions

View File

@ -11,12 +11,12 @@ Similar to `stream-pair`, but with sockets with real fds. A workaround for <http
```javascript ```javascript
var socketPair = require('socket-pair'); var socketPair = require('socket-pair');
socketPair.create(function (err, pair) { var socket = socketPair.create(function (err, other) {
var a = pair.client; // as in `client = net.connect()` // socket as in `client = net.connect()`
var b = pair.connection; // as in `server.on('connection', function (conn) { ... })` // other as in `server.on('connection', function (conn) { ... })`
a.write('123'); socket.write('123');
b.on('data', function (chunk) { other.on('data', function (chunk) {
console.log(chunk.toString('utf8')); console.log(chunk.toString('utf8'));
}); });

View File

@ -10,7 +10,7 @@ function createServer(cb, prefix) {
var path = require('path'); var path = require('path');
var sockname = (prefix || 'node-socket-pair') + '.' + require('crypto').randomBytes(16).toString('hex') + '.sock'; var sockname = (prefix || 'node-socket-pair') + '.' + require('crypto').randomBytes(16).toString('hex') + '.sock';
if (/win/.test(os.platform())) { if (/^win/.test(os.platform())) {
sock = path.join('\\\\?\\pipe', process.cwd(), sockname); sock = path.join('\\\\?\\pipe', process.cwd(), sockname);
} }
else { else {
@ -30,13 +30,13 @@ function createServer(cb, prefix) {
exports.create = function create(cb, prefix) { exports.create = function create(cb, prefix) {
var net = require('net'); var net = require('net');
var client; var client = new net.Socket();
function createConnection() { function createConnection() {
function onClientError(err) { function onClientError(err) {
cb(err); cb(err);
} }
client = net.connect(sock, function () { client.connect(sock, function () {
client.removeListener('error', onClientError); client.removeListener('error', onClientError);
}); });
client.once('error', onClientError); client.once('error', onClientError);
@ -48,7 +48,7 @@ exports.create = function create(cb, prefix) {
} }
server.once('connection', function onEach(connection) { server.once('connection', function onEach(connection) {
cb(null, { client: client, connection: connection }); cb(null, connection);
}); });
if (!listening) { if (!listening) {
@ -57,6 +57,8 @@ exports.create = function create(cb, prefix) {
else { else {
createConnection(); createConnection();
} }
return client;
}; };
exports.closeAll = function () { exports.closeAll = function () {