Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 387
Brian Avatar asked Apr 19 '13 13:04

Brian


People also ask

What is a file descriptor Nodejs?

A file descriptor is a reference to an open file, a number (fd) returned by opening the file using the open() method offered by the fs module. This number ( fd ) uniquely identifies an open file in operating system: JS copy.

How do you open a file in node JS?

flag: The operation in which file has to be opened. mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to default as readwrite. callback: It is a callback function that is called after reading a file.

What is writeFileSync in node JS?

writeFileSync() is a synchronous method, and synchronous code blocks the execution of program. Hence, it is preferred and good practice to use asynchronous methods in Node. js.

Is fs writeFile async?

writeFile() is an asynchronous method for writing data in files of any type.


1 Answers

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

like image 81
Noah Avatar answered Sep 30 '22 18:09

Noah