I am a beginner in node.js (infact started just today). One of the basic concepts is not clear to me, which I am asking here & couldn't find on SO.
Reading some tutorials on the web I wrote a client side & a server side code:
Server side (say server.js):
var http = require('http'); //require the 'http' module
//create a server
http.createServer(function (request, response) {
//function called when request is received
response.writeHead(200, {'Content-Type': 'text/plain'});
//send this response
response.end('Hello World\nMy first node.js app\n\n -Gopi Ramena');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Client side (say client.js):
var http=require('http');
//make the request object
var request=http.request({
'host': 'localhost',
'port': 80,
'path': '/',
'method': 'GET'
});
//assign callbacks
request.on('response', function(response) {
console.log('Response status code:'+response.statusCode);
response.on('data', function(data) {
console.log('Body: '+data);
});
});
Now, to run the server, I type node server.js
in the terminal or cmd prompt. & it runs successfully logs the message in the console & also outputs the response when I browse to 127.0.0.1:1337.
But, how to I run client.js? I could not understand how to run the client side code.
Server A (Client): log('1'); // Connect to server var io = require('socket. io-client'); var socket = io. connect('http://localhost:8080', {reconnect: true}); console.
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.
To address these issues, Node. JS uses a single thread with an event-loop. In this way, Node can handle 1000s of concurrent connections without any of the traditional detriments associated with threads. There is essentially no memory overhead per-connection, and there is no context switching.
Short answer: you can use the command
node client.js
to run your "client side" code, it will send one http request
Regarding to what's server side
and what's client side
, it's really depends on the context.
Although in most cases, client side
means the code running on your browser or your mobile phone app, server side
means the "server" or "back end" your browser or your mobile phone is talking to.
In your case, I think it's more like one "server" talks to another "server", and they are both on the back end, since that's what node.js is designed for
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With