Nodejs - Toidicode

Start from the beginning
                                        

-Thuộc tính này chứa các paramter trong URL mà client gửi lên server.

VD:

// khai báo sử dụng module HTTPvar http = require('http');//Khởi tạo server chạy cổng 8000http.createServer(function (request, response) { var param = request.url; response.write(param); response.end();}).listen(8000);

Lúc này các tiền tố phía sau domain sẽ được hiện ra nếu có: vd http://localhost:8000/toidicode thì url sẽ là /toidicode.


Bài 10: Đọc ghi file với module fs trong Node.js1, Module fs là gì?

-Module fs (viết tắt của file system) là một module được tích hợp sẵn trong node.js có chức năng xử lý file, thư mục trong node.js

2, Khai báo sử dụng module fs.

-Cũng giống như các module khác khi chúng ta muốn sử dụng được nó thì chúng ta cần phải require() nó.

Để require module fs chúng ta sử dụng cú pháp:

require('fs');

-Module fs này chứa rất nhiều các function dùng để xử lý file và thư mục. Để xem dạnh sách các phương thức trong module các bạn chỉ cần console.log() module ra.

VD:

var fs = require('fs');console.log(fs);3, Đọc file với module fs.

-Để đọc file với module fs chúng ta sử dụng phương thức readFile() với cú pháp:

readFile('pathFile',[option],function(err, data) { //});

Trong đó:

pathFile là đường dẫn của file cần đọc.option có thể là chuỗi hoặc mảng chứa các tùy chọn encode hay mode của file, nếu không cần cấu hình thì mọi người có thể bỏ trống.err là biến chứa lỗi nếu có.data là dữ liệu đọc được từ file.

VD: Mình sẽ kết hợp giữa kiến thức của bài trước và bài này để tiến hành đọc code HTML từ một file sang server để hiện thị

Đầu tiên chúng ta sẽ tạo một file code.html với nội dung như sau:

<!DOCTYPE html><html><head> <meta> <meta http-equiv="X-UA-Compatible"> <title>toidicode.com</title> <link></head><style> h1{ color: orange; text-align: center; }</style><body> <h1>Chào mừng bạn đã đến với website toidicode.com</h1></body></html>

Tiếp đó chúng ta cần tạo ra một file server.js cùng cấp với file code.html để khởi tạo server và xử lý file.

// khai báo sử dụng module HTTPvar http = require('http');//Khai báo sử dụng module fsvar fs = require('fs');//Khởi tạo server chạy cổng 8000http.createServer(function (req, res) { //định dang response head trả về res.writeHead('200',{'content-type' : 'text/html'}); //đọc file code.html encode utf8 fs.readFile('code.html','utf8',function(err, data) { if (err) throw err; // in ra nội dung đọc được res.write(data); //kết thúc response res.end();}); }).listen(8000);

Sau đó các bạn chạy file server lên và sẽ nhận được kết quả như sau:

4, Ghi file với module fs.

You've reached the end of published parts.

⏰ Last updated: Mar 02, 2018 ⏰

Add this story to your Library to get notified about new parts!

Nodejs - ToidicodeWhere stories live. Discover now