2016年1月28日 星期四

【Node.js】LEVEL 3 - Streams

3.2 File Read Stream

Lets use the fs module to read a file and log its contents to the console.

Task 1:
Use the fs module to create a Readable stream for fruits.txt. Store the new stream in a variable called file.

Task 2:
Next, listen to the readable event on the newly created stream and give it a callback.

Task 3:
Inside the callback, read the data chunks from the stream and print them to the console using console.log() - you might want to use a while loop to do this. Don't forget to call toString() on the data before printing it.

```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 Readable stream, let's use pipe to read from the stream and write directly to process.stdout.

Task 1:
Start by removing the code for the readable handler.

Task 2:
Call file.pipe(), passing it the stream to write to.

```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 end event.

Task 2:
Move the logic for handling the request from the http.createServer() callback to your new 'request' event listener. Remember to remove the http.createServer() callback once the code has been moved.

```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 index.html.

Task:
Use pipe() to send index.html to the response.

```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); ```

沒有留言:

張貼留言