nodeschool.io 4

~~ MY FIRST ASYNC I/O! ~~

Write a program that uses a single asynchronous filesystem operation
to read a file and print the number of newlines it contains to the
console (stdout), similar to running `cat file | wc -l`.

The full path to the file to read will be provided as the first
command-line argument.

----------------------------------------------------------------------
HINTS:

The solution to this problem is almost the same as the previous
problem except you must now do it the Node.js way: asynchronous.

Instead of `fs.readFileSync()` you will want to use `fs.readFile()`
and instead of using the return value of this method you need to
collect the value from a callback function that you pass in as the
second argument.

Remember that idiomatic Node.js callbacks normally have the signature:

function (err, data) { ... }

so you can check if an error occurred by checking whether the first
argument is truthy. If there is no error, you should have your
`Buffer` object as the second argument. As with `readFileSync()`,
you can supply 'utf8' as the second argument and put the callback as
the third argument and you will get a `String` instead of a `Buffer`.

Documentation on the `fs` module can be found by pointing your browser
here:
C:\Users\dzhang\AppData\Roaming\npm\node_modules\learnyounode\node_apidoc\fs.h
tml

var fs = require('fs');
fs.readFile(process.argv[2],"utf-8",function(err,data){
    if(err) throw err;
    console.log(data.split("\n").length-1);
});

 

转载于:https://www.cnblogs.com/della/p/3458183.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值