Endless
Endless

Reputation: 37786

Get filepath/name of a File Descriptor in node.js

How do you get fullpath from a file descriptor in node?

var fs = require('fs')
var fd = fs.openSync('package.json', 'r')

console.log(fd) // 10

console.log(get_file_path_from_fd(fd)) // HELP

Edit: I have found this

> fs.openSync('.', 'r')
10
> fs.readlinkSync('/proc/self/fd/10')
'/home/alfred/repos/test

but i didn't find proc folder in Mac

Upvotes: 1

Views: 1990

Answers (2)

Endless
Endless

Reputation: 37786

import { execSync } from 'node:child_process'
import { pid } from 'node:process'
import fs from 'node:fs'

const fd = fs.openSync('package.json', 'r')
const fullpath = execSync(`lsof -a -p ${pid} -d ${fd}`).toString().split('\n')[1].split(/\s+/).pop()

console.log(fullpath) // result: /fullpath/package.json

Upvotes: 1

Hectate
Hectate

Reputation: 212

Considering that you're loading a file that is in the same directory as the script, you could just use the __dirname global to find the current directory.

https://nodejs.org/docs/latest/api/globals.html#globals_dirname

In fact, I prefer to load files using __dirname as part of the path for the fs module as a good practice. For example, this is from a Discord bot I have...

var tokenJSON = require( __dirname + '/json/discord_token.json');

Edit: So to put this into the answer itself; your fd variable contains the data that was loaded from the file, but it is completely disconnected from the file it came from originally. If you are being given an arbitrary file to load and you would like to have the path, we need to know more about how that file is being provided to you. When the file is given to you there should be a path included (so the script can locate the data!) and that is what you want. If there is no path like in your example, then that means the relative paths are the same and it's the current directory.

Upvotes: 1

Related Questions