- Building Enterprise JavaScript Applications
- Daniel Li
- 386字
- 2021-07-23 16:31:10
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!.
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!:
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.