No need to set up a local server with Node.js? - javascript

I see when I want write a Node.js web application on my local machine, I don't need to set-up a local server using WAMP or MAMP. What is node.js really doing behind the scenes? I am providing this code to make a simple hello world web app:
var http = require("http");
http.createServer(function(request,response){
response.writeHead(200, {"content-type":"text/html"});
response.write("hello world");
response.end();
}).listen(8080);
console.log("server is running....");
When loading in my browser URL bar "localhost:8080" it works.
How this is working as and why don't I need a local server when working with Node.js?

You do have a local server... it's your Node.js application.
When you call http.createServer(), it creates an HTTP server. When you call .listen() on that server, it binds to the requested port, and optionally requested address, and listens for connections. When data comes in on those connections, it responds like any other HTTP server.
The HTTP server uses your request/response callback, firing it whenever a valid HTTP request comes in.

Because node comes out of the box with all the libraries you need to run a webserver, the http library that you are using is opening the 8080 port and handling the request with the function you provided
This part:
function(request,response){
response.writeHead(200, {"content-type":"text/html"});
response.write("hello world");
response.end();
}

No, you don't need it. Because node itself can be your webserver, just like in your example. Node is built on V8, which is chrome JavaScript engine .
Take a look a Express js module that gives you lots of features out of the box

Related

How to handle tcp/ip raw requests and http requests on the same server

I am working on a gps tracking system and have built a server on node js.
This is how the file looks like for reference.
const net = require('net');
const lora_packet = require('lora-packet');
const dataParser = require('./dataParser');
const clients = [];
net.createServer(function(socket) {
socket.name = socket.remoteAddress + ":" + socket.remotePort;
clients.push(socket);
socket.on('data', function(data) {
console.log("Buffer sent by terminal : ");
console.log(data);
const packet = lora_packet.fromWire(data, 'hex');
const str = packet._packet.PHYPayload.toString('hex');
dataParser.parse_data(str, socket);
});
socket.on('end', function() {
clients.splice(clients.indexOf(socket), 1);
//broadcast(socket.name + "has left the cartel.\n");
});
function broadcast(message, sender) {
clients.forEach(function(client) {
if (client === sender) client.write(message + "\nsent\n");
return;
client.write(message);
});
process.stdout.write(message);
}
}).listen(8080);
console.log("cartel is running on the port 8080\n");
This server file handles only requests from the hardware and processes raw tcp/ip requests.
I want the server to handle http requests also and want to incorporate routing feature in the server too for client side applicarions for browser.
1) Is there any way that http requests can also be handled by the same server or should I open another port and deploy an express node js app on that?
2) If I use the same 8080 port for http, how can the routing be achieved?
3) If I use different ports for http and raw tcp/ip, what would be the best way for communication between the two server. The communication between tcp/ip server and http server should happen via socket(sending data dynamically).
From http server using socket, data has to be sent dynamically to browser to update live location
So is the flow right?
Hardware (<---->)TCP/IP server(<--->)Http server(<--->)Browser
If more information is needed to solve the query, I'll provide with that!
Thank you
It's very complicated to try to speak multiple protocols on the same port. It requires some sort of scheme at the beginning of each connection to sample the incoming data and identify which protocol it is and then shunt that connection off to the right code to handle that protocol. I wouldn't suggest it.
It is way, way easier to just open a second server on a different port for an Express server to field your http requests. Very simple. You can do it right in the same app. Because both servers can be in the same app, you can just directly read from one connection and write to the other. There's no need for interprocess communication.
Is there any way that http requests can also be handled by the same server or should I open another port and deploy an express node js app on that?
Open another port. No need to write another app unless you have a specific reason to use two processes. You can put both the plain TCP server and the Express server in the same node.js app.
If I use the same 8080 port for http, how can the routing be achieved?
It's not easy. Not suggest to use the same port for multiple protocols.
If I use different ports for http and raw tcp/ip, what would be the best way for communication between the two server. The communication between tcp/ip server and http server should happen via socket(sending data dynamically).
You can put both servers in the same node.js app and then you can just read/write directly from one to the other with the same code. No need for interprocess communication.
From http server using socket, data has to be sent dynamically to browser to update live location
Sending data dynamically to a browser usually means you want the browser to hold something like a webSocket or socket.io connection to your server so you can then send data to the browser at any time over the existing connection. Otherwise, you would have to "wait" for the browser to request data and then respond with the data when it asks.

how to make a request to Ldap with client-side Javascript?

I should make a request to LDAP client side possibly with Javascript.
I searched in the web finding ldapjs that does what I want, but server side. This:
var ldap = require('ldapjs');
var server = ldap.createServer();
server.search('o=example', function(req, res, next) {
var obj = {
dn: req.dn.toString(),
attributes: {
objectclass: ['organization', 'top'],
o: 'example'
}
};
if (req.filter.matches(obj.attributes))
res.send(obj);
res.end();
});
server.listen(1389, function() {
console.log('LDAP server listening at %s', server.url);
});
So I tried using requirejs to import a library ldapjs client side, but was unable to make it work. There is no file called ldapjs to import.
I'm on the right track?
There are other ways?
I'm forced to stay on the client side
As long as you want to run your JavaScript in a web browser, you are limited to the HTTP protocol and to the domain from which your script was loaded in the first place.
So, talking to an LDAP server will not be possible from a web browsers JavaScript engine.
For do that install node.js and run your application locally.
use ldapjs to running in node to access the LDAP server and expose it to your standard http requests ( example: browser makes http request -> NodeJS runs LDAP JS Client---> connects to LDAP Server.)

External Hello world server node js

I am looking to use Node.js to host a web server on a dedicated PC, but I cant seem to access it from anywhere besides my local network.
From what Ive found online, it seems like all I have to do is enter the externalIp:port in a browser on a different network and I should see my Hello World, but I cant get it to work without exposing my localhost through something like ngrok.
Does anyone know how could I access my node server from an external pc on the internet and not just localhost?
Here are the steps to reproduce
require("http").createServer(function(request, response){
response.writeHeader(200, {"Content-Type": "text/plain"});
response.write("Hello World!");
response.end();
}).listen(8080);
"node server.js" - very simple server hosting on port 8080 that just sends 'Hello World!' response
check localhost:8080 on my machine, see "Hello World!" working
get externalIP from ipchicken.com
check 'externalIP':8080 on external machine (phone, diff network pc), never works
Maybe there is something I am missing, but I thought this was pretty straightforward
So it turns out the router I was using from Optimum has a "special" settings page to allow Port 80 traffic. And there is no link to it anywhere on the port forwarding page. So after doing all your port forwarding, make sure you follow this link:
http://optimumdev.custhelp.com/app/answers/detail/a_id/2140/related/1
You need to bind the service to all available ip interfaces, change your listen 8080 to :
require("http").createServer(function(request, response){
response.writeHeader(200, {"Content-Type": "text/plain"});
response.write("Hello World!");
response.end();
}).listen(8080, "0.0.0.0")
Assuming you have a standard home network setup, you can't just send a request to your external IP address and expect it to magically reach your machine. The request will hit your router and the router won't know what to do with it. You need to configure your router to forward requests on port 8080 to your local address (probably something like 192.168.0.x). Even that may not be enough. You may need to configure a software firewall on your machine to allow incoming requests on that port as well. Hope this helps :)

How to create a node.js server?

I'm trying to create my first node.js server and I have some problems.
When I use
var http = require("http");
var server = http.createServer();
server.listen(8888);
No connection can be established to the server.
But when I use this
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
The server lands ok.
I used this in a file called server.js and runned the command node server.js. I'm using v 0.12.0
What am I missing? Why the server doesn't work on the first case?
The first block of code creates a server and listens on a port.
When you point a browser at it, the browser makes a request and then waits for a response.
You haven't told the server what to respond with, so it sits there doing nothing.
Eventually the browser times out.
In the second set of code, you've told the server how to respond to requests.

Javascript Server Side Events with C-client Server Program

Im looking for feasibility of calling C object(for copying a file from client to server) via Javascript Eventsource.
Ex:
I have a C-Client Program which can be executed as below:
./client ip
executing above file will
send a file from client machine to server running at port 8888.
Server will be running at 8888 will receive the file and will write at /folder1/receivedfile.
./server ip
I need to do this in Javascript Event source.
Javascript code example:
if(window.EventSource){
var source =new EventSource("c-object");
}else{
// Result to xhr polling :( xhttprequest
}
It is feasible. Your second line would be something like this:
var source = new EventSource("http://myserver.example.com:8888/c-object");
Your server must be running HTTP protocol, of course. If going down this route, be aware that calling a resource on a different origin will need all the CORS workarounds. In this case the resource is c-object, and the different origin is because of using a different port to where the HTML was served from.
Alternatively you could use Apache, and start c-object as a cgi program. Then it just needs to interact on stdin/stdout.
But, taking a step back, are you sure it is EventSource you want? If you are just trying to send a signal to the server to tell it to copy a file, and not receiving any data, then use a normal AJAX request. SSE is for the server to stream data to the client, one-way, continuously. After the initial connection is made, SSE cannot send anything to the server.

Categories

Resources