Getting Started with NodeJS: Simple HTTP Server

Node.js uses an event-driven, non-blocking model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. This simple web server written in Node responds with “Hello World” for every request. To run the server, put the code into a file example.js and execute it with the node program from the command line.

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello Worldn');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

This is in contrast to today’s more common concurrency model where OS threads are employed. Thread-based networking is relatively inefficient and very difficult to use. Furthermore, users of Node are free from worries of dead-locking the process—there are no locks. Almost no function in Node directly performs I/O, so the process never blocks. Because nothing blocks, less-than-expert programmers are able to develop scalable systems.

Just because Node is designed without threads, doesn’t mean you cannot take advantage of multiple cores in your environment. You can spawn child processes that are easy to communicate with by using our child_process.fork() API. Built upon that same interface is the cluster module, which allows you to share sockets between processes to enable load balancing over your cores.

Onyx Theme Gutenberg Installing Nginx on Ubuntu 14.04 with Server Caching Faster Response Time with Reverse Proxy Cache
View Comments
  • Comments which are made by the author are marked with the ‘Author’ tag, such as this one. Replies to posts are indented. Disqus comment support can be enabled via the theme options as an alternative to the default WordPress comments.