问题
I have noticed what could be a big problem though for openSync, that when you open a file with openSync, you don't get the file descriptor. You only get it as an argument to the callback if you open with the asynchronous call. The problem is that you HAVE to have the file descriptor to close the file! There are other things which a programmer might want to do to a file that you need the file descriptor for as well.
It would seem a significant omission in the fs API for node.js not to provide a way to get access to the fd variable that the call back returns when opening in asynchronous mode if you open using synchronous calls. That would essentially make the synchronous open unuseable for most applications.
I really don't want to have to use the async file opens and closes later on in my development if I can avoid it, is there any way to get the fd variable I need to close the file successfully when using the synchronous open?
回答1:
What else would you get from openFileSync besides a file descriptor?
var fs = require('fs')
var path = require('path')
var fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')
fs.writeSync(fd, 'contents to append')
setTimeout(function () {
console.log('closing file now')
fs.closeSync(fd)
}, 10000)
Running lsof /path/to/log.txt
while the node script above is running and running lsof /path/to/log.txt
again after the script is done shows that the file is being closed correctly
That said what are you trying to accomplish by opening the file? Perhaps there is a better way such as streaming for your specific situation
来源:https://stackoverflow.com/questions/16106111/how-to-get-file-descriptor-in-node-js-if-you-open-file-using-opensync