เมื่อเราติดตั้ง Node.js เสร็จเรียบร้อย มาลองเขียนแอพพลิเคชั่นแรกด้วย Node.js กันครับ ก่อนเขียนก็หาเครื่องมือดีๆ ซักตัวสำหรับเขียน Node.js แนะนำตัวที่ใช้อยู่คือ Visual Studio Code เนื่องจากกินทรัพยากรเครื่องน้อย เปิดเร็ว และมี Add On ให้ติดตั้งเพิ่มเติมเยอะมาก ช่วยอำนวยความสะดวกในการเขียนโปรแกรมได้เป็นอย่างดี https://code.visualstudio.com
แอพพลิเคชั่นแรก เราจะลองสร้าง Server เมื่อเรียกมาที่ http://127.0.0.1:8081 จะส่งค่ากลับไปเป็น "Hello World"
สร้างโฟลเดอร์สำหรับพัฒนา Node.js ในเครื่องซักที่หนึ่ง ต่อมาสร้างไฟล์ main.js เขียนโค้ดคำสั่งตามด้านล่าง
var http = require("http");
http.createServer(function(request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
อธิบายโค้ด
var http = require("http");
Import โมดูล http ของ Node.js มาใช้งาน และเก็บมันไว้ในตัวแปร http | http เป็น Build In โมดูลของ Node.js ใช้สำหรับส่งข้อมูลผ่าน Hyper Text Transfer Protocol (HTTP)
http.createServer(function(request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
ใช้ตัวแปร http เรียกฟังก์ชั่น http.createServer(...) ในการสร้าง Server เพื่อรอรับ Request และส่งกลับค่า Response ให้กับคนที่เรียกใช้เข้ามาที่ port 8081 จากโค้ดเราจะส่งข้อมูลกลับไปเป็นชนิด text/plain เป็นข้อความ "Hello World"
สั่งทำงานได้โดยใช้คำสั่ง node ตามด้วยไฟล์ main.js
$ node main.js
ทดสอบเปิด Browser แล้ว พิมพ์ http://127.0.0.1:8081 จะได้ผลตามรูปด้านล่าง