2

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Sure. However, running echo 'Hello World!' > /tmp/test-socket still results in bash: /tmp/test-socket: No such device or address. (I expect to see "Hello World!" printed out.)
Did you use mknod or mkfifo to create the test-socket file?
I used the program in the OP.
Can you try creating the file using mkfifo? Then in the program don't unlink the file but just start listening to it. The file creation part of the library may be buggy.
If use rm /tmp/test-socket && mkfifo /tmp/test-socket and try to run my program I get Error: listen EADDRINUSE.
1

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 -

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.