0%

上一节课主要讲了在 node 中处理同步的 I/O;在 node 中大部分还是异步的情况。

课程内容:

课程目标:

1
2
3
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)

My Solution:

1
2
3
4
5
6
7
8
9
10
const fs = require("fs");
const file = process.argv[2];

fs.readFile(file, "utf8", (err, buf) => {
if (err) {
return console.err(err);
}
const result = buf.toString().split("\n").length - 1;
console.log(result);
});

Officical Solution:

1
2
3
4
5
6
7
8
var fs = require("fs");
var file = process.argv[2];

fs.readFile(file, function(err, contents) {
// fs.readFile(file, 'utf8', callback) can also be used
var lines = contents.toString().split("\n").length - 1;
console.log(lines);
});

课程总结

fs.readFile(path[,options],callback)异步 I/O(和fs.readFileSync()相对应)

  • path <string> | <Buffer> | <URL> | <integer> filename or file descriptor
  • options <Object> | <string>
    • encoding <string> | <null> Default: null
    • flag <string> Default: ‘r’
  • callback <Function>
    • err <Error>
    • data <string> | <Buffer>