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

16,019

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

Share:
16,019
Brian
Author by

Brian

I'm a passionate professional software engineer and I strive to create simple software solutions that are scalable, readable, and maintainable.

Updated on June 14, 2022

Comments

  • Brian
    Brian almost 2 years

    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?

  • Brian
    Brian about 11 years
    thanks for the quick answer! Used your example and you are right, it works like a charm. That makes sense that it would return fd after openSync, the API just didn't say it explicitly and I didn't think to try it before posting question. I'm simply trying to log some timing data to file for a test on my system, I'm a C/C++ guy trying to figure out node.js on my own and files are familiar to me, but I will go check out streams on your suggestion to see if they might fit better for me in node. Thanks again!
  • Noah
    Noah about 11 years
    No problem. The node.js docs are nice for the most part. Sometimes though they assume a lot of the reader and are a little bit over-truncated