-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparallelprocessing.js
More file actions
62 lines (54 loc) · 1.73 KB
/
parallelprocessing.js
File metadata and controls
62 lines (54 loc) · 1.73 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
const fs = require('fs');
const csv = require('csv-parser');
const { Transform } = require('stream');
const createCsvStringifier = require('csv-writer').createObjectCsvStringifier;
// Readable Stream for reading the CSV file
const readStream = fs.createReadStream('data/input.csv')
.pipe(csv());
// Transform Stream 1: Filter users older than 30
const filterAgeStream = new Transform({
objectMode: true,
transform(chunk, encoding, callback) {
if (parseInt(chunk.age) > 22) {
this.push(chunk);
}
callback();
}
});
// Transform Stream 2: Filter users from a specific city (e.g., 'New York')
const filterCityStream = new Transform({
objectMode: true,
transform(chunk, encoding, callback) {
if (chunk.city === 'New York') {
this.push(chunk);
}
callback();
}
});
// Writable Streams for storing the results
const ageResultStream = fs.createWriteStream('users_over_22.csv');
const cityResultStream = fs.createWriteStream('users_in_ny.csv');
// Create CSV stringifiers for writing CSV data
const ageCsvStringifier = createCsvStringifier({
header: [
{ id: 'name', title: 'Name' },
{ id: 'age', title: 'Age' },
{ id: 'city', title: 'City' },
],
});
const cityCsvStringifier = createCsvStringifier({
header: [
{ id: 'name', title: 'Name' },
{ id: 'age', title: 'Age' },
{ id: 'city', title: 'City' },
],
});
// Pipe the data through parallel streams
readStream
.pipe(filterAgeStream)
.on('data', (data) => ageResultStream.write(ageCsvStringifier.stringifyRecords([data])))
.on('end', () => ageResultStream.end());
readStream
.pipe(filterCityStream)
.on('data', (data) => cityResultStream.write(cityCsvStringifier.stringifyRecords([data])))
.on('end', () => cityResultStream.end());