Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run node.js client on browser

everyone

I'm very new to node.js. I'm trying to do a tcp server <-> client using node.js. So far so good. The server script can be run Ok. Also the client script can be run OK.

But the problem is I could only get the client to run from the terminal by typing command (node client.js).
The thing is I would like to run it in a browser so I could take the data received from server display on browser.

How do I do that?

Please help.

Kawin.

This is the client code. (I can't remember who originally created this script. I copy and paste it from somewhere but forget to bookmark from which I get the link. Sorry for not putting the credit to the owner of this script.)

var net = require('net');

var HOST = '192.168.0.88';
var PORT = 8888;

var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the   server will receive it as message from the client 
    client.write('B2\r\n');
});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
    console.log('DATA: ' + data);
    // Close the client socket completely
    client.destroy();
});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
}); 

Thank you.

like image 338
Kawin Netvichitpan Avatar asked Jan 21 '15 04:01

Kawin Netvichitpan


People also ask

Can you run node JS in the browser?

It is possible to execute JavaScript on both the browser and Node. js which are both built around a JavaScript engine that provides the execution environment for JS code.

Does node JS run on client side browser?

js application. In client-side we mainly deal with DOM or web APIs like cookies, but these things don't exist in Node. Other reasons why we cannot use node modules at the client side is that the node uses the CommonJS module system while the browser uses standard ES Modules which has different syntax.

How do I run node js in Chrome?

The next step is to head to Chrome, open a new tab, and enter the URL chrome://inspect/ . Click on “Open dedicated DevTools for Node” to start debugging the application. It will take a couple of seconds to view the source code in Chrome DevTools.


1 Answers

Node.js is not browser javascript. There are many parts of it that use OS features not available in a browser context. The way to do what you're looking to do while staying in the browser for the client, is to not use a TCP socket, but instead look into WebSockets (e.g. socket.io, which offers server and browser clients).

like image 55
Paul Avatar answered Oct 21 '22 13:10

Paul