Building Enterprise JavaScript Applications
上QQ阅读APP看书,第一时间看更新

Creating an HTTP server

Next, we need to set up our project so that it can run ES6 code, specifically the ES6 modules feature. To demonstrate this, and also to show you how to debug your code, we're just going to create a simple HTTP server that always returns the string Hello, World!.

Normally, when we follow a TDD workflow, we should be writing our tests before we write our application code. However, for the purpose of demonstrating these tools, we will make a small exception here.

Node.js provides the HTTP module, which contains a createServer() method (https://nodejs.org/api/http.html#http_http_createserver_requestlistener)that allows you to provision HTTP servers. At the root of your project directory, create an index.js file and add the following:

const http = require('http');
const requestHandler = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!');
}
const server = http.createServer(requestHandler);
server.listen(8080);

We are able to use ES6 syntax (such as const) here because ES2015 support has been good since Version 6 of Node. But ES6 modules are still unsupported, even in the latest version of Node. Therefore, we are using CommonJS's require syntax instead.
Later in this chapter, we will demonstrate how to convert our source code to be written with the ES6 modules feature, using Babel to transpile it back to the universally supported CommonJS syntax.
To see the level of support for ES2015+ features in different versions of Node, go to node.green.

Once you've done that, open up a terminal and run node index.js. This should have started a server on localhost:8080. Now, if we send a request to localhost:8080, for instance by using a web browser, it'll return with the text Hello, World!:

If you get an  Error: listen EADDRINUSE :::8080  error, it means something else is using port   8080; in that case, either terminate the process bound to port 8080, or choose a different port instead by changing the number passed into  server.listen().

The node process is currently running in the foreground and will continue to listen for further requests. To stop the node process (and thus our server), press Ctrl + C.

Pressing   Ctrl + C  sends an interrupt signal ( SIGINT) to the Node program, which handles it and terminates the server.