Search code examples
node.jsfs

fs.appendFileSync(path) call closes file handle in node.js?


There are two apis 1)fs.appendFileSync(path) which takes in path of the file and 2)fs.appendFileSync(fd) which takes in file descriptor, the second one doesnt close the file handle which makes sense cause its borrowed from outside of the function, but what about the the first call? Since a fd is made internal to function does it closes it? No docs mentioned about the first overloaded api? Also of the fd is open internally how do i acquire to close it?

https://nodejs.org/docs/latest-v16.x/api/fs.html#fsappendfilesyncpath-data-options


Solution

  • According to the lib/fs.js code, fs.appendFileSync() does close the file when it is complete.

    if (!isUserFd) fs.closeSync(fd) is called at the end of the process, closing the file if the fd wasn't passed in.

    Here are the links to Node.JS 16.x code from the Node project on GitHub - I tried to match source version with the version docs you were looking at.

    function appendFileSync(path, data, options) { https://github.com/nodejs/node/blob/b8a8c83dffea8422db003e9444d4526ebafbd36a/lib/fs.js#L2222

    function writeFileSync(path, data, options) { https://github.com/nodejs/node/blob/b8a8c83dffea8422db003e9444d4526ebafbd36a/lib/fs.js#L2159

    Hope that helps.