Published on

ทำความรู้จัก .pipe() ใน Node.js

ทำความรู้จัก .pipe() ใน Node.js
ทำความรู้จัก .pipe() ใน Node.js

อันยองงง สวัสดีคุณผู้อ่านทุกท่านเน้อครับ วันนี้เจมส์จะมาเขียนบทความ "ทำความรู้จัก .pipe() ใน Node.js" ในตอนที่เขียนบทความเรื่อง "ทำ API ให้แสดงไฟล์ PDF บน Express" แล้วได้ใช้งานคำสั่ง .pipe() เลยอยากรู้เพิ่มเติมเลยไปศึกษามา จนเป็นที่มาของบทความนี้ครับ

.pipe() คืออะไร

.pipe() เป็น Method ที่ใช้ใน Node.js ซึ่งจะทำงานกับข้อมูลที่เป็น Stream ทำงานในส่วนที่เป็นการอ่าน (Readable) และการเขียน (Writeable) ถ้าจะเปรียบให้เห็นภาพ เปรียบเหมือนกับท่อ PVC ที่รับส่งน้ำ โดยน้ำเปรียบเสมือนข้อมูล

ส่วน .pipe() คือข้อต่อที่รับน้ำและส่งน้ำต่อไป

เราจะใช้ .pipe() ตอนไหน

เราควรจะใช้ .pipe() ตอนที่เราต้องการอ่านข้อมูลแบบ Stream และเอาข้อมูลที่ได้จากการอ่าน ไปเขียนต่อไป เพื่อความเข้าใจมากยิ่งขึ้น ลองมาดูตัวอย่างการใช้งานกันครับ

อ่านข้อมูลจาก File หนึ่ง และเขียนใส่อีก File หนึ่ง

const fs = require('fs')

// อ่านข้อมูลจากไฟล์ data.txt
const readableStream = fs.createReadStream('data.txt')

// เขียนข้อมูลใส่ไฟล์ destination.txt
const writableStream = fs.createWriteStream('destination.txt')

// ใช้ .pipe() เพื่ออ่านข้อมูลจาก readableStream เอาข้อมูลที่ได้ไปเขียนใน writableStream
readableStream.pipe(writableStream)

แบบ Response ข้อมูลที่อ่านส่งออกไปยัง HTTP Server

const http = require('http')
const fs = require('fs')

const server = http.createServer((req, res) => {
  const readableStream = fs.createReadStream('data.txt')

  // .pipe() เพื่อโยกย้ายข้อมูลจาก Readable Stream ไปยัง Writable Stream (HTTP Response)
  readableStream.pipe(res)
})

server.listen(3000, () => {
  console.log('Server is listening on port 3000')
})

แบบ Response ข้อมูลที่อ่านส่งออกไปยัง HTTP Server ในแบบนี้จะเหมือนกับบทความ ทำ API ให้แสดงไฟล์ PDF บน Express เพียงแต่ในส่วนขั้นตอนการ Readable เจมส์ดึงข้อมูลจาก API มาแทนการอ่านจาก file ตรงๆ

ทำเป็น gzip

// Node.js program to demonstrate the
// createGzip() method

// Including zlib and fs module
const zlib = require('zlib')
const fs = require('fs')

// Creating readable Stream
const inp = fs.createReadStream('data.txt')

// Creating writable stream
const out = fs.createWriteStream('data.txt.gz')

// Calling createGzip method
const gzip = zlib.createGzip()

// Piping
inp.pipe(gzip).pipe(out)
console.log('Gzip created!')

หลัก ๆ ที่คิดว่าน่าจะได้ใช้ประมาณนี้ครับ หวังว่าบทความนี้จะมีประโยชน์กับคุณผู้อ่านเน้อครับ หากคุณผู้อ่านมีข้อสงสัยหรืออยากสอบถาม สามารถคอมเม้นท์ทิ้งไว้ได้เน้อครับ

Reference

Practical Guide: Learn How to Use .pipe() in Node.js

Node.js zlib.createGzip() Method