1

在 node.js 中同步和异步检查现有文件有什么区别?

例如:

var path = require('path');
if (path.existsSync("/the/path")) { // or fs.existsSync
    // ...
}

// Is it a directory?
lstat('/the/path', function(err, stats) {
    if (!err && stats.isDirectory()) {
        // Yes it is
    }
});
4

1 回答 1

1

方法的同步版本fs通过方法的返回值提供它们的结果;因此,这些方法必须在执行 I/O 以确定结果时阻塞。

异步版本通过调用者作为参数提供给方法的方法的回调函数提供它们的结果。这些方法只是启动所需的 I/O,然后立即返回,因此这些方法的返回值没有用处。当 I/O 稍后完成时,将调用回调以将结果返回给调用者。

于 2012-11-12T05:44:40.313 回答