60 phút
Node.js Fundamentals
Giới thiệu Node.js
Node.js là một runtime environment để chạy JavaScript trên server.
Module System
CommonJS Modules
// Export
module.exports = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
// Import
const math = require('./math');
console.log(math.add(2, 3));
ES6 Modules
// Export
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// Import
import { add, subtract } from './math.js';
Built-in Modules
File System
const fs = require('fs');
// Đọc file
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Ghi file
fs.writeFile('file.txt', 'Hello World', (err) => {
if (err) throw err;
console.log('File saved!');
});
HTTP Module
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
NPM và Package.json
Khởi tạo project
npm init -y
Cài đặt package
npm install express
npm install --save-dev nodemon
Scripts
{
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
}
}
Bài tập tiếp theo
Chúng ta sẽ học về Express.js framework!