How to get file descriptor in node.js if you open a file with openSync

I noticed that this can be a big problem, although for openSync, when you open a file using openSync you will not get a file descriptor. You can only use this as an argument for a callback if you open an asynchronous call. The problem is that you have a file descriptor to close the file! There are other things that a programmer might want to do with a file for which you need a file descriptor.

It would seem that a significant omission in the fs API for node.js should not provide a way to access the fd variable returned by the callback when opened in asynchronous mode if you open it using synchronous calls. This will greatly simplify the synchronous opening for most applications.

I really don't want to use an async file that opens and closes later in my development, if I can avoid it, is there a way to get the fd variable I need to close the file successfully when using synchronous open?

+6
source share
1 answer

What else could you get from openFileSync besides the 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 when the node script above is executed and lsof /path/to/log.txt is lsof /path/to/log.txt again after the script is executed shows that the file is closing correctly

Said what are you trying to do by opening a file? Perhaps there is a better way, for example, streaming for your specific situation.

+13
source

All Articles