Skip to content

Commit 90b9784

Browse files
Merge pull request #40 from FACN1/streams-and-buffers
Streams and buffers
2 parents 7c886d5 + cae72ec commit 90b9784

File tree

9 files changed

+48183
-0
lines changed

9 files changed

+48183
-0
lines changed

week-5/streamsAndBuffers/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

week-5/streamsAndBuffers/illiad.txt

Lines changed: 26175 additions & 0 deletions
Large diffs are not rendered by default.

week-5/streamsAndBuffers/mobydick.txt

Lines changed: 21831 additions & 0 deletions
Large diffs are not rendered by default.

week-5/streamsAndBuffers/out.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
hello
2+
my
3+
name
4+
is
5+
this

week-5/streamsAndBuffers/package.json

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"name": "streams-and-buffers",
3+
"version": "1.0.0",
4+
"description": "Learn about streams",
5+
"main": "readStr.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"author": "Mavis and Jack",
10+
"license": "ISC",
11+
"devDependencies": {
12+
"split": "^1.0.0"
13+
}
14+
}

week-5/streamsAndBuffers/readStr.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
const fs = require('fs');
2+
3+
//Need to require this to split by lines
4+
const split = require('split');
5+
6+
// our programm can take three flags, which are then assigned below, or default with the OR operator:
7+
var filepath = process.argv[2]||'./test.txt'
8+
var hwm = process.argv[3] || 100
9+
var timeout = process.argv[4] || 500
10+
11+
// Create the readable stream of the filepath specified and the hwm and set the econding to utf8
12+
var file = fs.createReadStream(filepath, {highWaterMark:hwm, encoding: 'utf8'});
13+
14+
//creat empty data
15+
var data =''
16+
17+
//You pipe the readable stream into split which sends it back as chunks split by a new line
18+
file.pipe(split())
19+
20+
//listen for error event
21+
file.on('error', function(err) {
22+
console.log('Error '+err);
23+
return err
24+
});
25+
26+
//listen for data events
27+
file.on('data', function(bits) {
28+
29+
//add new bits to the data str
30+
data +=bits
31+
32+
//print the new bit as a string (it comes buffered)
33+
process.stdout.write(bits);
34+
35+
//pause the reading
36+
file.pause();
37+
38+
//set a timeout as specified by the flag (def: 500ms) to then resume the read
39+
setTimeout(() => {
40+
file.resume();
41+
}, timeout);
42+
})
43+
44+
// listen for the end event
45+
file.on('end', function(){
46+
console.log('Finished reading all of the data');
47+
});
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Streams & Buffers
2+
3+
### 1) Streams
4+
5+
#### Data Access in Node
6+
- Fully buffered access vs. partially buffered access - these differ in terms of:
7+
- How the data is exposed
8+
- The amount of memory used to store the data
9+
10+
#### Fully Buffered Access
11+
- Asynchronous `readFile()`
12+
- Synchronous `readFileSync()`
13+
- The data is returned in **one big chunk** after all of it has been read
14+
- Node needs to allocate enough memory to store all of that data
15+
16+
#### Partially Buffered Access
17+
- Asynchronous `read()` `createReadStream()`
18+
- Synchronous `readSync()`
19+
- Data input is treated as a **series of events**, occurring as the data is being read or written - this allows us to **access data as it is being read**
20+
- Partially-buffered methods (listed above) allow us to specify the size of the buffer and read the data in small chunks
21+
22+
#### Streams
23+
- Streams are a form of **partially buffered access**
24+
- Streams return small pieces of data (using a buffer) and trigger an event when each new piece of data is available for processing
25+
- Since streams are partially buffered, we can process each piece of data **as soon as it is read** - this means we don't necessarily need to buffer / save the whole file into memory
26+
- The Node stream interface consists of two parts:
27+
- Readable streams
28+
- Writeable streams
29+
30+
#### Readable Streams
31+
- Readable streams emit the following events:
32+
- `data` emits a buffer / string
33+
- `end` is emitted when the stream receives an EOF (End of Function) - this indicates that there will be no more `data` events
34+
- `error` is emitted if there's an error receiving data
35+
- To bind a callback to an event, use `stream.on(eventname, callback)` - the HTTP request object is one example of a readable stream that we've already covered:
36+
- `request.on('error', function(err) { ... });`
37+
- `request.on('data', function(data) { ... });`
38+
- `request.on('end', function() { ... });`
39+
- Readable streams also have the following methods:
40+
- `request.pause()` pauses incoming data events
41+
- `request.resume()` resumes after a `pause()`
42+
- `request.destroy()` stops the stream emitting any more events
43+
44+
### 2) Buffers
45+
- In Node, buffers are a **high-performance alternative** to strings, representing raw C memory allocation
46+
- Buffers act like fixed-size arrays of integers, each represented as a **hexidecimal number** when run through `console.log()`
47+
48+
```js
49+
var buffer = new Buffer(10);
50+
buffer[0] = 255;
51+
console.log(buffer); // <Buffer ff 00 00 00 00 4a 00 00 00 00>
52+
```
53+
- Since buffers represent raw memory, any buffer content you haven't assigned (anything other than `buffer[0]` in the above example) will be whatever happens to sit in that position in memory (e.g. the `4a` seen above)
54+
- Compared to strings, buffers are fixed in size, and have very limited predefined functions (missing convenient ones like `String.replace()` for example)
55+
- If you want to use string functions on buffers, you can convert them to strings with `buffer.toString()` first
56+
57+
## Resources
58+
- http://book.mixu.net/node/ch9.html
59+
- https://www.sitepoint.com/basics-node-js-streams/
60+
- https://www.tutorialspoint.com/nodejs/nodejs_streams.htm

week-5/streamsAndBuffers/test.txt

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
this is just a test of this line repeated a lotx1
2+
this is just a test of this line repeated a lotx2
3+
this is just a test of this line repeated a lotx3
4+
this is just a test of this line repeated a lotx4
5+
this is just a test of this line repeated a lotx5
6+
this is just a test of this line repeated a lotx6
7+
this is just a test of this line repeated a lotx7
8+
this is just a test of this line repeated a lotx8
9+
this is just a test of this line repeated a lotx9
10+
this is just a test of this line repeated a lotx10
11+
this is just a test of this line repeated a lotx11
12+
this is just a test of this line repeated a lotx12
13+
this is just a test of this line repeated a lotx13
14+
this is just a test of this line repeated a lotx14
15+
this is just a test of this line repeated a lotx15
16+
this is just a test of this line repeated a lotx16
17+
this is just a test of this line repeated a lotx17
18+
this is just a test of this line repeated a lotx18
19+
this is just a test of this line repeated a lotx19
20+
this is just a test of this line repeated a lotx20
21+
this is just a test of this line repeated a lotx21
22+
this is just a test of this line repeated a lotx22
23+
this is just a test of this line repeated a lotx23
24+
this is just a test of this line repeated a lotx24
25+
this is just a test of this line repeated a lotx25
26+
this is just a test of this line repeated a lotx26
27+
this is just a test of this line repeated a lotx27
28+
this is just a test of this line repeated a lotx28
29+
this is just a test of this line repeated a lotx29

week-5/streamsAndBuffers/writeStr.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
//Require the file system module
2+
var fs = require('fs');
3+
4+
5+
//Create a writeable stream (i.e. a stream we can write to, which will go to ./out.txt)
6+
var file = fs.createWriteStream('./out.txt');
7+
8+
//Process.stdin (opposite of process.stdout) is a readable stream, that reads data that we input into the terminal
9+
10+
//So here when we read data from process.stdin.on we write that data to our file, the writable stream we created
11+
process.stdin.on('data', function(data) {
12+
file.write(data);
13+
});
14+
15+
//When the readable stream ends, we close the writeable stream
16+
process.stdin.on('end', function() {
17+
file.end();
18+
});
19+
20+
//Resume the incoming data stream after a pause
21+
process.stdin.resume();

0 commit comments

Comments
 (0)