Code ví dụ Node.js Hello World (console, web)
(Xem lại: Giới thiệu Node.js | Hướng dẫn cài đặt, cấu hình Node.js)
Yêu cầu: máy bạn đã phải cài Node.js
Ví dụ Node.js Hello World trên console
Tạo file hello_console.js với nội dung:
console.log('hello world!');
Thông thường với javascript, ta sẽ incluđe file hello_console.js vào một file html sau đấy mở file html bằng trình duyệt. Ví dụ:
<script src="hello_console.js"></script>
Nhưng với Node.js thì ta không cần phải mở bằng trình duyệt vì nó đã có sẵn engine để chạy file javascript.
Để chạy file hello_console.js bằng Node.js ta làm như sau:
Mở màn hình console và cd tới thư mục chứa file hello_console.jssau đó chạy lệnh node hello_console.js
Ví dụ mình để file hello_console.js ở trong thư mục C:\nodejs
Ví dụ Node.js Hello World trên web http
Tạo file hello_web.js với nội dung:
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
console.log('Server Started!');
var http = require('http'): include module http vào file (mình sẽ nói về module trong node.js ở bài sau)
http.createServer: Tạo server http.
Demo: mở màn hình cmd và cd tới thư mục chứa file hello_web.jssau đó chạy lệnh node hello_web.js
Mở trình duyệt web và nhập địa chỉ: localhost:8080
Okay, Done!
Download code ví dụ trên tại đây.
References: https://www.w3schools.com/nodejs/nodejs_get_started.asp