The First Node.js Web Server - Hello World


Node.js

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Download for Node.js

Install Node.js with the downloaded file.

The version of my downloaded file is node-v8.9.4-x64.msi as windows installer for 64-bit.

Install Node.js to the directory : C:\Program Files\nodejs\

Download code editor - Visual Studio Code

How to get started with Node.js after installing it?

Build The First Node.js Web Server : Hello World

Open Visual Studio Code.

Create a file named app.js.

Paste the following code:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Debug and run the program.

Server running at http://127.0.0.1:3000/

Paste the url http://127.0.0.1:3000/ on the browser and you get "Hello World".

張貼留言

0 留言