Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS: net.Socket is not a constructor

Tags:

node.js

The below code works fine if I run it from my command line, but if I run this code anywhere in my project I get this error:

net.Socket is not a constructor

I've tried making the below code an object and importing / requiring it into my project and I still get that error.

var net = require('net');

var client = new net.Socket();
    client.connect(3000, '127.0.0.1', function() {
    console.log('Connected');
    client.write('Hello, server! Love, Client.');
});

Am I miss understanding what require does, I also tried using import and import * as to obtain 'net'.

I'm not too sure what information would be useful in the situation. Any suggestions would be great.

like image 665
Adam Edney Avatar asked Feb 06 '23 17:02

Adam Edney


1 Answers

There are no plain TCP sockets in the browser, so that is why trying to use net.Socket in the browser (via webpack, browserify, etc.) won't work.

There could be a "polyfill" of sorts that requires a server to make the TCP connection on the browser's behalf though (or perhaps via some bridge to a Flash or Java applet).

like image 196
mscdex Avatar answered Feb 08 '23 10:02

mscdex