跳到主要内容
CNode

一个fs.readFileSync的问题

社区
Hhanai发布于 13 年前最后回复 13 年前
7293860
var fs = require('fs');

fs.readFile('file.txt', 'utf-8', function(err, data) {
	if(err) {
    	console.error(err);
    } else {
	    console.log(data);
    }
});
console.log('end.');

var data2 = fs.readFileSync('file.txt', 'utf-8');
console.log(data2);
console.log('end.');

这段程序的执行结果为什么是

end.
Contents of the file.
end.
Contents of the file.

而不是下面这样的呢?

end.
Contents of the file.
Contents of the file.
end.
查看回复

回复 (7)

A
ahmzj#713 年前

.readFile的回调函数是异步的,所以在这里的console在下面的语句执行完后,才执行的

C
cgwang#513 年前
引用 cgwangreadFile 是异步的,会在当前代码段执行完毕之后才会执行读取文件的操作,所以data在最后一行才被打印出来;而readFileSync是同步读取文件内容

@Hanai 没有影响。是打印出来的语句一样,导致你看得时候有一些混淆。 你试着用下面的代码运行一下,应该就明白了。

var fs = require('fs');

fs.readFile('file.txt', 'utf-8', function(err, data) {
    if(err) {
        console.error(err);
    } else {
	    console.log("readFile");
    }
});
console.log('end. of readFile');

var data2 = fs.readFileSync('file.txt', 'utf-8');
console.log("readFileSync");
console.log('end. of readFileSync');
H
hanai#413 年前
引用 cathcn因为交叉了

交叉?

H
hanai#313 年前
引用 cgwangreadFile 是异步的,会在当前代码段执行完毕之后才会执行读取文件的操作,所以data在最后一行才被打印出来;而readFileSync是同步读取文件内容

不明白。 单独

var data2 = fs.readFileSync('file.txt', 'utf-8');
console.log(data2);
console.log('end.');

我知道data2会在end.上面,可是为什么,前面添加了异步的readFile()变成这样

fs.readFile('file.txt', 'utf-8', function(err, data) { ... });
console.log('end.');

var data2 = fs.readFileSync('file.txt', 'utf-8');
console.log(data2);
console.log('end.');

后会对同步的readFileSync()产生影响,让data2跑到了end.下面。

C
cgwang#213 年前

readFile 是异步的,会在当前代码段执行完毕之后才会执行读取文件的操作,所以data在最后一行才被打印出来;而readFileSync是同步读取文件内容

C
cathcn#113 年前

因为交叉了

参与回复

登录后即可参与回复。登录