Traditionally, developers only used the JavaScript language in web browsers. But, in 2009, Node.js was unveiled, and with it, the developer tool kit expanded greatly. Node.js gave developers the chance to use JavaScript to write software that, up to that point, could only be written using C, C++, Java, Python, Ruby, C#, and the like.
We will use Node to write server code. Specifically, web services that communicate with clients using the JavaScript Object Notation (JSON) format for data interchange.
To write a simple web server with Node.js
:
HTTP
module to abstract away complex network-related operations.The request handler is a function that takes the request
coming from the client and produces the response
. The function takes two arguments: 1) an object representing the request
and 2) an object representing the response
.
This process works, but the resulting code is verbose, even for the simplest of servers. Also, note that when using only Node.js to build a server, we use a single request handler function for all requests.
Using only Node.js, let's write a simple web server that returns a message. Create a folder for the server and add an index.js
file inside.
Next, add the following code to the index.js
file:
const http = require("http"); // built in node.js module to handle http traffic
const hostname = "127.0.0.1"; // the local computer where the server is running
const port = 3000; // a port we'll use to watch for traffic
const server = http.createServer((req, res) => {
// creates our server
res.statusCode = 200; // http status code returned to the client
res.setHeader("Content-Type", "text/plain"); // inform the client that we'll be returning text
res.end("Hello World from Node\n"); // end the request and send a response with the specified message
});
server.listen(port, hostname, () => {
// start watching for connections on the port specified
console.log(`Server running at http://${hostname}:${port}/`);
});
Now navigate to the folder in a terminal/console window and type: node index.js
to execute your file. A message that reads "Server running at http://127.0.0.1:3000" should be displayed, and the server is now waiting for connections.
Open a browser and visit: http://localhost:3000
. localhost
and the IP address 127.0.0.1
point to the same thing: your local computer. The browser should show the message: "Hello World from Node". There you have it, your first web server, built from scratch using nothing but Node.js
.
Write a paragraph about what Node.js
is and explain at least 3 of its core features.
Consider addressing the following points in your response:
The versions of project dependencies used in the recording are slightly different from the ones used in the starter and solution repositories, but this should not affect the relevant code of the Guided Project.
The versions used in the repositories are more recent, and thus more similar to the versions you will install if you create a project from scratch.