我有以下快速代码:
protocol Animal {
var name: String { get }
}
struct Bird: Animal {
var name: String
var canEat: [Animal]
}
struct Mammal: Animal {
var name: String
}
extension Array where Element: Animal {
func mammalsEatenByBirds() -> [Mammal] {
var eatenMammals: [Mammal] = []
self.forEach { animal in
if let bird = animal as? Bird {
bird.canEat.forEach { eatenAnimal in
if let eatenMammal = eatenAnimal as? Mammal {
eatenMammals.append(eatenMammal)
} else if let eatenBird = eatenAnimal as? Bird …Run Code Online (Sandbox Code Playgroud) 我正在尝试学习一些事件驱动编程的基础知识.因此,对于练习,我正在尝试编写一个程序,该程序读取大型二进制文件并使用它执行某些操作但不进行阻塞调用.我想出了以下内容:
var fs = require('fs');
var BUFFER_SIZE = 1024;
var path_of_file = "somefile"
fs.open(path_of_file, 'r', (error_opening_file, fd) =>
{
if (error_opening_file)
{
console.log(error_opening_file.message);
return;
}
var buffer = new Buffer(BUFFER_SIZE);
fs.read(fd, buffer, 0, BUFFER_SIZE, 0, (error_reading_file, bytesRead, buffer) =>
{
if (error_reading_file)
{
console.log(error_reading_file.message);
return;
}
// do something e.g. print or write to another file
})
})
Run Code Online (Sandbox Code Playgroud)
我知道我需要设置一个while循环以便读取完整的文件,但在上面的代码中我只读取文件的前1024个字节,并且不能制定如何在不使用阻塞循环的情况下继续读取文件.我们怎么能这样做?