1.3. Khởi tạo ứng dụng node.js với Hello world

1. Khởi tạo dự án Node.js

  • Tạo thư mục mới cho dự án:

mkdir my-first-app
cd my-first-app
  • Khởi tạo package.json

npm init -y

2. Tạo file index.js

  • Tạo file chính index.js: Trong thư mục my-first-app vừa tạo ở bước trên, tạo file index.js

const http = require('http');

const hostname = 'localhost';
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}/`);
});

Chạy ứng dụng

  1. Chạy server:

node index.js
  1. Kiểm tra kết quả:

    • Mở trình duyệt và truy cập vào địa chỉ: http://localhost:3000

    • Màn hình sẽ hiển thị dòng chữ "Hello World".

Last updated