3.2 File Read Stream
Lets use the
Task 1:
Use the
Task 2:
Next, listen to the
Task 3:
Inside the callback, read the data chunks from the stream and print them to the console using
```js var fs = require('fs'); var file = fs.createReadStream('fruits.txt'); file.on('readable', function(){ while(null !== (chunk = file.read())){ console.log(chunk.toString()); } }); ```
3.3 File Piping
Instead of manually listening for the 'readable' event on the
Task 1:
Start by removing the code for the
Task 2:
Call
```js var fs = require('fs'); var file = fs.createReadStream('fruits.txt'); file.pipe(process.stdout); ```
3.4 Fixing Pipe
The following code will throw an error because pipe automatically closed our writable stream.
Task 1:
You'll need to consult the pipe documentation to figure out the option which keeps the Write stream open and dispatches the
Task 2:
Move the logic for handling the request from the
```js var fs = require('fs'); var file = fs.createReadStream('origin.txt'); var destFile = fs.createWriteStream('destination.txt'); file.pipe(destFile, { end: false }); file.on('end', function(){ destFile.end('Finished!'); }); ```
3.5 Download Server
Let's create an HTTP server that will serve
Task:
Use
```js var fs = require('fs'); var http = require('http'); http.createServer(function(request, response) { response.writeHead(200, {'Content-Type': 'text/html'}); var file = fs.createReadStream('index.html'); file.pipe(response); }).listen(8080); ```
沒有留言:
張貼留言