File Read Stream

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

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

fs.createReadStream('fruits.txt');

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

file.on('readable', function(){});

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.

file.on('readable', function(){
while(null !== (chunk = file.read())){
console.log(chunk.toString());
}
});
var fs = require('fs');
var file = fs.createReadStream('fruits.txt'); file.on('readable', function(){
while(null !== (chunk = file.read())){
console.log(chunk.toString());
}
});

File Piping

Instead of manually listening for the 'readable' event on theReadable stream, let's use pipe to read from the stream and write directly to process.stdout.

Start by removing the code for the readable handler.

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

var file = fs.createReadStream('fruits.txt');
file.pipe(process.stdout);

Read More: http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options

For example, emulating the Unix cat command:

process.stdin.pipe(process.stdout);
var fs = require('fs');

var file = fs.createReadStream('fruits.txt');
file.pipe(process.stdout);

Fixing Pipe

The following code will throw an error because pipe automatically closed our writable stream.

You'll need to consult the pipe documentation to figure out the option which keeps the Write stream open and dispatches the end event.

  By default end() is called on the destination when the source stream emits end, so that destination is no longer writable. Pass{ end:   false } as options to keep the destination stream open.

file.pipe(destFile, { end: false });
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!');
});

Download Server

Let's create an HTTP server that will serve index.html.

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

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

[Node.js] Level 3 new. Steam的更多相关文章

  1. [Node.js] Level 7. Persisting Data

    Simple Redis Commands Let's start practicing using the redis key-value store from our node applicati ...

  2. [Node.js] Level 6. Socket.io

    6.2 Setting Up socket.io Server-Side So far we've created an Express server. Now we want to start bu ...

  3. [Node.js] Level 2 new. Event

    Chat Emitter We're going to create a custom chat EventEmitter. Create a new EventEmitter object and ...

  4. [Node.js] Level 5. Express

    Express Routes Let's create an express route that accepts GET requests on'/tweets' and responds by s ...

  5. A chatroom for all! Part 1 - Introduction to Node.js(转发)

    项目组用到了 Node.js,发现下面这篇文章不错.转发一下.原文地址:<原文>. ------------------------------------------- A chatro ...

  6. Node.js开发者最常范的10个错误

    目录 前言 1 不使用开发工具 1.1 自动重启工具 1.2 浏览器自动刷新工具 2 阻塞event loop 3 频繁调用回调函数 4 圣诞树结构的回调(回调的地狱) 5 创建一个大而完整的应用程序 ...

  7. Node.js的线程和进程

    http://www.admin10000.com/document/4196.html 前言 很多Node.js初学者都会有这样的疑惑,Node.js到底是单线程的还是多线程的?通过本章的学习,能够 ...

  8. Windows下Node.js+Express+WebSocket 安装配置

    Linux参考: Linux安装Node.js 使用Express搭建Web服务器 Node.js是一个Javascript运行环境(runtime).实际上它是对Google V8引擎进行了封装.V ...

  9. 为什么 Node.js 这么火,而同样异步模式 Python 框架 Twisted 却十几年一直不温不火?

    twisted是一个强大的异步网络框架,应用的面也非常广,但是没有这几年才出现的Node.js火,社区.文档也是很少可怜我觉得二者其实在本质上差不多,而且python使用起来还是比较容易一些的 匿名用 ...

随机推荐

  1. JavaSE基础之JDBC

    JavaSE基础之JDBC 1.JDBC 的步骤: ①加载数据库驱动: a.MySQL:com.mysql.jdbc.Driver: b.SQLServer:com.microsoft.jdbc.sq ...

  2. springboot中使用JOIN实现关联表查询

    * 首先要确保你的表和想要关联的表有外键连接 repository中添加接口JpaSpecificationExecutor<?>,就可以使用springboot jpa 提供的API了. ...

  3. hdu 5316 Magician(2015多校第三场第1题)线段树单点更新+区间合并

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5316 题意:给你n个点,m个操作,每次操作有3个整数t,a,b,t表示操作类型,当t=1时讲a点的值改 ...

  4. MyBatis -- generator 逆向工程

    一.引言 官网文档:http://www.mybatis.org/generator/index.html 通过使用官方提供的mapper自动生成工具,mybatis-generator-core-1 ...

  5. python IDLE 自动提示功能

    \Python27\Lib\idlelib\目录下 config-extensions.def文件修改等待时间 [AutoComplete] enable=1 popupwait=2000(2000表 ...

  6. Codeforces Round #354 (Div. 2) C. Vasya and String 二分

    C. Vasya and String 题目连接: http://www.codeforces.com/contest/676/problem/C Description High school st ...

  7. CGI 、PHP-CGI、FASTCGI、PHP-FPM

    CGI是干嘛的? CGI是为了保证web server传递过来的数据是标准格式的,方便CGI程序的编写者.web server(比如说nginx)只是内容的分发者.比如,如果请求的是/index/ht ...

  8. IO流-复制多极文件夹(递归实现)

    package com.io.test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ...

  9. 轨至轨运算放大器 rail to rail

    http://www.360doc.com/content/10/1102/16/2285160_66006645.shtml Rail to rail: 轨至轨,指器件的输入输出电压范围可以达到电源 ...

  10. USB Mass Storage Class – Bulk Only Transport - Error Handling

    6.4 Device Error Handling The device may not be able to fully satisfy the host's request. At the poi ...