Get filepath/name of a File Descriptor in node.js - 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

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.

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

Related

Setting path of fs.appendFileSync?

How do you set the path of fs.appendFileSync? For example, I want to make a file in folder "X" but my code is in the folder above. How would I create the file in another folder than the one my code is in(the file is made in the same folder as the source code).
I've read the documentation but I don't understand how I would be able to specify where to create the file.
The variable __dirname represents the directory that the currently running script is located in. So, if you wanted to put a file in a sub-directory below that (let's say it is in a variable called someDir), then you would do that like this:
const path = require('path');
let pathToFile = path.join(__dirname, someDir, "filename.txt");
fs.appendFileSync(pathToFile, dataToWrite);
If that directory doesn't yet exist and you need to create it, then you could use fs.mkDirSync() to create i.
const path = require('path');
// make sure sub-directory is created
let dirForFile = path.join(__dirname, someDir);
if (!fs.existsSync(dirForFile) {
fs.mkDirSync(dirForFile);
}
// append data to the file
let pathToFile = path.join(dirForFile, "filename.txt");
fs.appendFileSync(pathToFile, dataToWrite);

Access variable from another file

I have ex1.js and ex2.js. And in ex2.js I want to get variable which one is in ex1.js
I can read the file, but I want to get exactly this var Value.
var fs = require('fs');
var readMe = fs.readFileSync('path', 'utf8');
console.log(readMe);
As long as they are both JavaScript files this is how it is generally done.
// in the js2 file
exports.var_js2 = 15;
// in the js1 file
var_js2 = require('./js2').var_js2

How can i read a json file in gzip?

There is an archive format gzip. There are json files. We need to get each file in turn , to do with it and what is written in the other gzip. I realized that I need to use the standard library createReadStream and zlib.
Well, following the example from https://nodejs.org/api/zlib.html#zlib_examples the following process could be done for a single gzipped file:
var unzip = zlib.createUnzip();
var fs = require('fs');
var inp = fs.createReadStream('input.json.gz');
var out = fs.createWriteStream('output.json');
inp.pipe(unzip).pipe(out);
However if there are multiple files within a gzip, I am not sure how one would go about doing that. I could not find documentation to do that and the only way I found that multiple files could be unzipped from a gzip file in node is if they were tar'd first. A process for unzipping tar.gz in node can be found here. Following that example, one could do something like this:
var unzip = zlib.createUnzip();
var fs = require('fs');
var tar = require('tar-fs');
var inp = fs.createReadStream('input.tar.gz');
var out = './output'; // output directory
inp.pipe(unzip).pipe(tar.extract(out));

Get file name from absolute path in Nodejs?

How can I get the file name from an absolute path in Nodejs?
e.g. "foo.txt" from "/var/www/foo.txt"
I know it works with a string operation, like fullpath.replace(/.+\//, ''),
but I want to know is there an explicit way, like file.getName() in Java?
Use the basename method of the path module:
path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'
Here is the documentation the above example is taken from.
To get the file name portion of the file name, the basename method is used:
var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var file = path.basename(fileName);
console.log(file); // 'python.exe'
If you want the file name without the extension, you can pass the extension variable (containing the extension name) to the basename method telling Node to return only the name without the extension:
var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var extension = path.extname(fileName);
var file = path.basename(fileName,extension);
console.log(file); // 'python'
var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.parse(filepath).name;
console.log(name); //python
var base = path.parse(filepath).base;
console.log(base); //python.exe
var ext = path.parse(filepath).ext;
console.log(ext); //.exe
For those interested in removing extension from filename, you can use
https://nodejs.org/api/path.html#path_path_basename_path_ext
path.basename('/foo/bar/baz/asdf/quux.html', '.html');
If you already know that the path separator is / (i.e. you are writing for a specific platform/environment), as implied by the example in your question, you could keep it simple and split the string by separator:
'/foo/bar/baz/asdf/quux.html'.split('/').pop()
That would be faster (and cleaner imo) than replacing by regular expression.
Again: Only do this if you're writing for a specific environment, otherwise use the path module, as paths are surprisingly complex. Windows, for instance, supports / in many cases but not for e.g. the \\?\? style prefixes used for shared network folders and the like. On Windows the above method is doomed to fail, sooner or later.
path is a nodeJS module meaning you don't have to install any package for using its properties.
import path from 'path'
const dir_name = path.basename('/Users/Project_naptha/demo_path.js')
console.log(dir_name)
// returns
demo_path.js
In NodeJS, __filename.split(/\|//).pop() returns just the file name from the absolute file path on any OS platform.
Why need to care about remembering/importing an API while this regex approach also letting us recollect our regex skills.
So Nodejs comes with the default global variable called '__fileName' that holds the current file being executed
My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic
Below, I make use of the fileName string and then split it based on the path.sep. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.
You can write a service like this (Note this is in typescript , but you can very well write it in js )
export class AppLoggingConstants {
constructor(){
}
// Here make sure the fileName param is actually '__fileName'
getDefaultMedata(fileName: string, methodName: string) {
const appName = APP_NAME;
const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
//const actualFileName = fileName;
return appName+ ' -- '+actualFileName;
}
}
export const AppLoggingConstantsInstance = new AppLoggingConstants();

Retrieving files from Directory Node Js

I am using readDirSync to get the files from a Diretory. PLease find the code and error as following.
var fs = require('fs');
var files = fs.readdirSync('./application/models/');
for(var i in files) {
var definition = require('../application/models/'+files[i]).Model;
console.log('Model Loaded: ' + files[i]);
}
I am getting error for line number 2 .
ENOENT, No such file or directory './application/models/' at Object.readdirSync (fs.js:376:18)
I have application/models on the same dir. I already checked for '/application/models/' and
'application/models/' but failed. I can see the same thing running on server.
Please help
Thanks
If you are using relative path when calling readdirSync, make sure it is relative to process.cwd().
However, "require" should be relative to the current script.
For example, given the following structure
server.js (node process)
/lib/importer.js (the current script)
/lib/application/models/
you may need to write importer.js as:
var fs = require('fs');
var files = fs.readdirSync('./lib/application/models/');
for (var i in files) {
var definition = require('./application/models/' + files[i]).Model;
console.log('Model Loaded: ' + files[i]);
}
Have you tried the following?
var files = fs.readdirSync(__dirname+'/application/models/');

Resources