File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -799,6 +799,37 @@ async function () {
799799// b
800800```
801801
802+ Node v10 支持异步遍历器,Stream 就部署了这个接口。下面是读取文件的传统写法与异步遍历器写法的差异。
803+
804+ ``` javascript
805+ // 传统写法
806+ function main (inputFilePath ) {
807+ const readStream = fs .createReadStream (
808+ inputFilePath,
809+ { encoding: ' utf8' , highWaterMark: 1024 }
810+ );
811+ readStream .on (' data' , (chunk ) => {
812+ console .log (' >>> ' + chunk);
813+ });
814+ readStream .on (' end' , () => {
815+ console .log (' ### DONE ###' );
816+ });
817+ }
818+
819+ // 异步遍历器写法
820+ async function main (inputFilePath ) {
821+ const readStream = fs .createReadStream (
822+ inputFilePath,
823+ { encoding: ' utf8' , highWaterMark: 1024 }
824+ );
825+
826+ for await (const chunk of readStream ) {
827+ console .log (' >>> ' + chunk);
828+ }
829+ console .log (' ### DONE ###' );
830+ }
831+ ```
832+
802833### 异步 Generator 函数
803834
804835就像 Generator 函数返回一个同步遍历器对象一样,异步 Generator 函数的作用,是返回一个异步遍历器对象。
You can’t perform that action at this time.
0 commit comments