'How to create a socket connection with a path

In the docs, there is a function to create a socket via a path,
it's socket.connect(path[, connectListener]) link

I tried this:

var net = require('net'),
    fs = require('fs'),
    path = require('path'),
    sock,
    os = require('os');

const TEMP_DIR = os.tmpDir();
const TEMP_FILE = path.join(TEMP_DIR, 'my.sock');

console.log(TEMP_FILE)

fs.open(TEMP_FILE, 'w+', function(err, fdesc){
    if (err || !fdesc) {
        throw 'Error: ' + (err || 'No fdesc');
    }
    sock = new net.Socket({
      fd : fdesc,
      allowHalfOpen: true,
      readable: true,
      writable: true
    });
});

But getting this error:

net.js:32
  throw new TypeError('Unsupported fd type: ' + type);
  ^

TypeError: Unsupported fd type: FILE
    at createHandle (net.js:32:9)
    at new Socket (net.js:128:20)
    at /Users/timaschew/dev/myproject/test.js:20:12
    at FSReqWrap.oncomplete (fs.js:82:15)

I also tried other flags: w, a+, a, but the same erorr.

I'm using node v4.2.0 on OSX 10.11.13

I'm searching for a solution without using a port and with native node modules. And it would be also nice if it's working on linux, osx and windows.



Solution 1:[1]

You should use server.listen(PATH):

const net = require('net');
const path = require('path');
const os = require('os');

// Returns the operating system's default directory for temporary files as a string.
const TEMP_DIR = os.tmpdir();
const TEMP_FILE = path.join(TEMP_DIR, 'my.sock');

net.createServer(...).listen(TEMP_FILE);

socket.connect() is to connect to an existing domain socket (in other words, to implement the client side).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user5204695