-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreams.js
More file actions
68 lines (56 loc) · 1.89 KB
/
Copy pathstreams.js
File metadata and controls
68 lines (56 loc) · 1.89 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const fs = require('fs');
/*
* Read a file using a readable stream
* @param {string} fileName - The name of the file to read from
* @returns {Promise} - A promise that resolves when the file is read from
*/
const readFileStream = (fileName) => {
return new Promise((resolve, reject) => {
console.log("Stream | Reading file: ", fileName);
const readableStream = fs.createReadStream(fileName);
readableStream.on('data', (chunk) => {
// Split the chunk into lines and log the lines that start with 'Test'
chunk.toString().split('\n').forEach(line => {
if (line.startsWith('Test')) {
console.log("Chunk: ", line.trim());
}
});
});
readableStream.on('end', () => {
console.log('End of stream');
resolve();
});
readableStream.on('error', (error) => {
console.log('Error: ', error.message);
reject(error);
});
});
}
/*
* Write to a file using a writable stream
* @param {string} fileName - The name of the file to write to
* @returns {void} - This function does not return a Promise
*/
const writeFileStream = (fileName) => {
console.log("Stream | Writing to file: ", fileName);
const writableStream = fs.createWriteStream(fileName);
writableStream.on('data', (chunk) => {
console.log("Chunk: ", chunk.toString());
});
writableStream.on('end', () => {
console.log('End of stream');
});
writableStream.on('error', (error) => {
console.log('Error: ', error.message);
throw new Error(error.message);
});
writableStream.write('Hello, world!');
writableStream.end();
}
main = () =>{
const fileNames = ['input.txt', 'outpu.txt'];
readFileStream(fileNames[0]).then(() => {
writeFileStream(fileNames[1]);
});
}
main();