Full-Stack Web Development with Vue.js and Node

(singke) #1
Building an Express Application Chapter 2

Now, run the file with this command:


$ node tutorial.js

We will see an output that says Hello World. This is how we execute files in Node.js.


Other than running on the V8 engine and executing JavaScript codes in a web browser,


Node.js also provides a server running environment. This is the most powerful feature of


Node.js. Node.js provides an HTTP module of itself that enables a non-blocking HTTP
implementation. Let's build a simple web server to understand this.


On the same file, in tutorial.js, overwrite the file with the following code:


const http = require('http');

http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(8080, '127.0.0.1');

console.log('Server running at http://127.0.0.1:8080/');

Here, the var http = require('http'); code requires the HTTP module into our


application. It means that now we can access the functions defined in the HTTP library via
the http variable. Now we need to create a web server. The preceding code tells Node.js to


run the web server in the 8080 port. The function parameter in the createServer


method takes two arguments, req and res, which are the short form of request and


response respectively. The first thing that we need to do inside that function is to set the


HTTP header. This is basically defining what type of response we want from that request.
Then, we define what we want to get in the response by using res.send. Finally, we ask


the web server to listen to port 8080.


When we run this code with $ node tutorial.js, the output looks like this:

Free download pdf