-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode-streams-util.js
43 lines (39 loc) · 1.04 KB
/
node-streams-util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { Readable, Writable } from "node:stream";
import db from "./database.js";
// Function to fetch data from the database
const fetchData = (offset, chunkSize) =>
new Promise((resolve, reject) => {
db.all(
"SELECT title, release_date, tagline FROM movies LIMIT ? OFFSET ?",
[chunkSize, offset],
(err, rows) => (err ? reject(err) : resolve(rows))
);
});
// Create a readable stream
const CHUNK_SIZE = 10;
let offset = 0;
export const createMovieReadableStream = new Readable({
objectMode: true,
async read() {
try {
const rows = await fetchData(offset, CHUNK_SIZE);
if (rows.length) {
rows.forEach((row) => this.push(row));
offset += CHUNK_SIZE;
} else {
this.push(null); // End of stream
}
} catch (err) {
this.destroy(err);
}
},
});
export const createMovieWritableStream = () => {
return new Writable({
objectMode: true,
write(movie, encoding, callback) {
console.log(movie); // Process the movie data here
callback();
},
});
};