Jackson Ray Hamilton
Jackson Ray Hamilton

Reputation: 9466

Node.js Unix socket not echoing

I am trying to create a file which I can cat or echo strings to and receive strings back as output. If I understand correctly I can do this with a Unix socket.

I've tried to write a server but I can't seem to get it to recognize my input:

'use strict';

var net = require('net'),
    fs = require('fs'),
    socketAddress = '/tmp/test-socket',
    server;

server = net.createServer(function (client) {
    var whole = '';
    client.on('data', function (data) {
        whole += data;
    });
    client.on('end', function () {
        client.write(whole);
    });
});

fs.unlink(socketAddress, function (error) {
    if (error && error.code !== 'ENOENT') {
        throw error;
    }
    server.listen(socketAddress, function () {
        console.log('Socket listening at ' + socketAddress);
    });
});

I try to do echo 'Hello World!' | /tmp/test-socket and I get bash: /tmp/test-socket: No such device or address. But ls -l /tmp yields:

srwxr-xr-x 1 jackson jackson 0 Jun 1 01:10 test-socket

Please advise on how I can get this socket to echo the strings I write to it.

Upvotes: 2

Views: 332

Answers (2)

Mehrdad Nazmdar
Mehrdad Nazmdar

Reputation: 192

The /tmp/test-socket is not a file. It's a socket file. That's what the leading s means in srwxr-xr-x. Bash's redirection like > does not support socket files. With socat (a 'bidirectional data relay between two data channels') you can connect to the unix domain socket like this:

echo 'Hello World!' | socat UNIX-CONNECT:/tmp/test-socke -

Upvotes: 1

slebetman
slebetman

Reputation: 113926

test-socket is not a program. The pipe operator (|) tries to execute the next argument (in this case test-socket) as a program or script and pass the output to its stdin.

Since sockets (named pipes) are essentially files, you need to use the > or >> operator:

echo 'Hello World!' > /tmp/test-socke

This of course assumes that your node code is working.

Upvotes: 1

Related Questions