Phần 9: NodeJS – Streams – NodeJS căn bản cho người mới bắt đầu

Phần  9: NodeJS – Streams                        – NodeJS căn bản cho người mới bắt đầu

Stream là gì?

Stream là những đối tượng giúp bạn đọc dữ liệu từ 1 nguồn và ghi dự liệu tới 1 đích. Trong Node.js, có 4 loại Stream.
Readable – Là Stream được dùng để cho hoạt động đọc
Writable – Là Stream được dùng cho hoạt động ghi
Duplex – Là Stream được dùng cho cả mục đích ghi và đọc
Transform – Đây chính là 1 kiểu Duplex Stream, khác ở chỗ là kết quả đầu ra được tính toán dựa vào dữ liệu bạn đã nhập vào.
Từng loại Stream là 1 sự thể hiện của đối tượng EventEmitter và ném một số sự kiện ở các thời điểm khác nhau. Danh sách sau liệt kê những sự kiện thường được dùng:
knowledge – Sự kiện này được bật khi dữ liệu là có sẵn cho hoạt động đọc.
finish – Sự kiện này được bật khi không còn dữ liệu nào để đọc nữa.
error – Sự kiện này được bật khi xảy ra bất kỳ lỗi nào ở trong việc đọc và ghi dữ liệu.
end – Sự kiện này được bật khi toàn bộ dữ liệu được chuyển hết đến vùng hệ thống cơ sở.
Phần tiếp theo mình sẽ trình bày chi tiết những hoạt động thường sử dụng trên những Stream.

Đọc dữ liệu từ Stream trong Node.js

Đầu tiên, bạn tạo 1 textual content file với tên enter.txt có nội dung sau:
Tutorials Point is giving self studying content material
to show the world in easy and straightforward manner!!!!!
Tạo 1 js file có tên most important.js. Trong file này, đầu tiên bạn khai báo fs Module (đây chính là Module cho những hoạt động File I/O) do sử dụng phương thức require(). Sau đó sử dụng phương thức createReadStream() nhận tham số là tên của textual content file bạn đã tạo trước đây để đọc dữ liệu từ đấy.
var fs = require("fs");
var knowledge = '';

// Create a readable stream
var readerStream = fs.createReadStream('enter.txt');

// Set the encoding to be utf8. 
readerStream.setEncoding('UTF8');

// Handle stream occasions --&gt knowledge, finish, and error
readerStream.on('knowledge', operate(chunk) );

readerStream.on('finish',operate() );

readerStream.on('error', operate(err) {
   console.log(err.stack);
});

console.log("Program Ended");
Hiện tại chạy most important.js để xem kết quả:
$ node most important.js
Kiểm tra kết quả đầu ra:
Program Ended
Tutorials Point is giving self studying content material
to show the world in easy and straightforward manner!!!!!

Ghi dữ liệu đến Stream trong Node.js

Bạn cũng tạo 1 most important.js như ở trên. Khác ở chỗ là thay vì sử dụng createReadStream(), bạn sử dụng phương thức createWriteStream() nhận tham số là file để chứa kết quả bạn phải ghi:
var fs = require("fs");
var knowledge = 'Simply Easy Learning';

// Create a writable stream
var authorStream = fs.createWriteStream('output.txt');

// Write the information to stream with encoding to be utf8
authorStream.write(knowledge,'UTF8');

// Mark the tip of file
authorStream.finish();

// Handle stream occasions --&gt end, and error
authorStream.on('end', operate() 
   console.log("Write accomplished.");
);

authorStream.on('error', operate(err) {
   console.log(err.stack);
});

console.log("Program Ended");
Hiện tại chạy most important.js để xem kết quả:
$ node most important.js
Kiểm tra kết quả:
Program Ended
Write accomplished.
Hiện tại, bạn mở output.txt được tạo trong folder hiện giờ và kiểm tra nội dung kết quả nhận được:
Simply Easy Learning

Khái niệm Piping Stream trong Node.js

Piping là 1 kỹ thuật. Với kỹ thuật này, ta cung cấp kết quả đầu ra của 1 Stream để làm dữ liệu đầu vào cho 1 Stream khác. Không có giới hạn nào về hoạt động Piping này, tức là quá trình trên có thể vẫn đang tiếp tục.
Để hiểu thêm về khái niệm này, bạn theo dõi ví dụ sau đây. Trong ví dụ này, mình đọc dữ liệu từ 1 file, rồi ghi dữ liệu đó đến 1 file khác.
Đầu tiên, bạn tạo js file có tên most important.js ví dụ. Trong file này, bạn sử dụng 2 phương thức đã trình bày bên trên là createReadStream() và createWriteStream() tương ứng để đọc và ghi dữ liệu. Tiếp đó, sử dụng phương thức pipe() để thực hiện kỹ thuật Piping Stream như dưới đây:
var fs = require("fs");

// Create a readable stream
var readerStream = fs.createReadStream('enter.txt');

// Create a writable stream
var authorStream = fs.createWriteStream('output.txt');

// Pipe the learn and write operations
// learn enter.txt and write knowledge to output.txt
readerStream.pipe(authorStream);

console.log("Program Ended");
Chạy most important.js để xem kết quả:
$ node most important.js
Kiểm tra kết quả:
Program Ended
Mở output.txt được tạo trong folder hiện giờ của các bạn và kiểm tra nội dung:
Tutorials Point is giving self studying content material
to show the world in easy and straightforward manner!!!!!

Khái niệm Chaining Stream trong Node.js

Chaining là 1 kỹ thuật để kết nối kết quả đầu ra của 1 Stream đến 1 Stream khác và tạo 1 chuỗi gồm nhiều hoạt động Stream. Thường thì nó được dùng với những hoạt động Piping.
Ví dụ sau minh họa cách kết hợp 2 hoạt động Piping và Chaining. Đầu tiên ta nén 1 file, rồi giải nén file đó.
Tạo most important.js. Trong file này, mình cần khai báo zlip Module cung cấp phương thức createGzip() cho hoạt động nén.
var fs = require("fs");
var zlib = require('zlib');

// Compress the file enter.txt to enter.txt.gz
fs.createReadStream('enter.txt')
   .pipe(zlib.createGzip())
   .pipe(fs.createWriteStream('enter.txt.gz'));
  
console.log("File Compressed.");
Chạy most important.js để xem kết quả:
$ node most important.js
Kiểm tra kết quả:
File Compressed.
Sau khi kiểm tra, bạn sẽ thấy rằng enter.txt được nén và nó đã tạo 1 enter.txt.gz trong folder hiện giờ. Hiện tại, bạn thử giải nén cùng file trên do sử dụng phương thức createGunzip() của zlib Module như dưới đây:
var fs = require("fs");
var zlib = require('zlib');

// Decompress the file enter.txt.gz to enter.txt
fs.createReadStream('enter.txt.gz')
   .pipe(zlib.createGunzip())
   .pipe(fs.createWriteStream('enter.txt'));
  
console.log("File Decompressed.");
Chạy most important.js để xem kết quả:
$ node most important.js
Kiểm tra kết quả:
File Decompressed.

 

 

admin

Leave a Reply

Your email address will not be published. Required fields are marked *