我需要打开或关闭文件才能通过Node.js读取文件吗?

Do I need to open or close the file to read the file through Node.js?

以下函数读取文件正确,但我想知道这是否是读取文件的正确方法?

我需要使用 fs.open & fs.close 来读取文件吗?

如果没有,什么情况下需要使用fs.open&fs.close

fs.readFile(dbWrapper.baseDir+path+"/"+file+".json", 'utf8', 
       function(error, fileDesc){
            if(!error && fileDesc){
                callback(fileDesc);
            } else {
                callback(error);
            }
    });

Do I need to use fs.open & fs.close to read the file?

If not, In what cases do I need to use fs.open & fs.close?

这取决于你的要求。

fs.readFile()

Returns文件的全部内容在callback中,这个很简单,满足大部分人的需要。

fs.open()

Returns File Descriptor,您可以在其中使用文件描述符进行进一步的 fs.read() 调用。

如果您只需要文件的一部分,这会更复杂但更灵活。