誰能通过这段代码简单讲讲 被异步了 是啥意思 = =
发布于 11 年前 作者 cooldrine 4162 次浏览 最后一次编辑是 8 年前

var fs = require(‘fs’);

var data = fs.readFile(’./aaa.txt’, ‘utf-8’)

console.log(data);

console.log(‘Damn’);

run后显示data没有定义,就是data被异步执行了吧,异步是啥意思呢在这里

3 回复

fs.readFile这个方法的结果是异步返回的,就是用回调函数传回的. 所以你这里打印的值是未定义的.

你可以用这个方法 var data = fs.readFileSync(’./aa.txt’, ‘utf-8’)

这个方法是同步执行的.

fs.read(fd, buffer, offset, length, position, callback)# Read data from the file specified by fd.

buffer is the buffer that the data will be written to.

offset is offset within the buffer where reading will start.

length is an integer specifying the number of bytes to read.

position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.

The callback is given the three arguments, (err, bytesRead, buffer).

用callback来提取内容吧

回到顶部