הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Welcome To Node

Node.JS is a tool for writing web servers, created by Ryan Dahl. It's written in JavaScript and runs on the Google V8 javascript engine.

Node takes a different approach than traditional web server. Usually, a web server has an abstraction layer that connects the web applications which runs inside to the outside world. The web server connects and mediates between the web applications and the HTTP client.
Node, on the other hand, is a collection of libraries and modified JavaScript interpreter that gives the developers tools to easily write a web server. This means a Node application is not ran inside a server, but rather is itself the server.

Node has several ready-made libraries that allow a developer to parse and repsond to HTTP requests, listen to netwrork traffic and work with multiple clients.
Being written in JavaScript means Node is based on a single thread of execution, and ran inside an event loop.
Most of the system calls node provides are async, and take a callback functions instead of blocking the thread.

In order to build a Web Server in Node, we'll simply take an existing library and add to it the functionality we need.

Hello Node.JS

Let's start with a quick example to writing a web server. Our simple server can take HTTP requests from clients and always responds with the same line: "RESISTANCE IS FUTILE".

/**
 * Node.JS Simple HTTP Server Demo
 *
 */

// require loads a module
var http = require('http');

// handler takes a request and reponse object
// and handles the request.
// This code is called for every HTTP request arriving
// to your server
var handler = function(request, response) {
  console.log('A New Request From: ' + request.socket.remoteAddress );

  response.writeHead(200);
  response.write('RESISTANCE IS FUTILE');
  response.end();
};

// createServer takes a handler callback and calls it for every request
var server = http.createServer( handler );

// listen starts to listen on a port
server.listen(8080);

Note request and response objects are created for you in the http server module. You can read more about them in the Module's Documentation.