Adding a variable to __dirname -- Javascript - javascript

I am trying to add a variable to __dirname because I want to navigate folders depending on that but it doesn't seem to work.
Isn't this the correct way to do so?
var directory = '/some_folder/';
fs.readdir(__dirname + directory, function(err, files){
// code
}
To be more precise, I have a folder like so:
A_folder
some_folder
some_other_folder
..
And knowing __dirname is A_folder I want to access the other folders depending on what my "directory" variable is.

Use path.join() to get absolute path. Pass relative path as second argument.
var path = require('path');
var directory = path.join(__dirname, './some_folder');
fs.readdir(directory, function(err, files){
// code
}

Related

How to res.sendFile() a file that is in a different directory for Express.js webapp?

I have this inside controllers folder:
//controler.js
exports.serve_sitemap = (req, res) => {
res.sendFile("../../sitemap.xml");
// or
// res.send(__dirname + "./sitemap.xml")
// But neither of these work
};
This exported function is imported in a file inside the routes directory
const { serve_sitemap } = require('../controllers/indexer')
var router = require('express').Router()
router.get("/sitemap", serve_sitemap)
module.exports = router
Currently I am getting a 404 error when I try to get the sitmap at localhost:3000/sitemap
Folder Structure:
Before, I had the same thing in index.js which is the entry point.
app.get("/sitemap", (req, res) => {
res.sendFile(__dirname + "/sitemap.xml");
});
This was working perfectly, until I decided to restructure the project
How can I refer to the sitemap.xml file that is located in the root directory from a file that is in a sub-directory when using res.send()?
How can I get the absolute path to the root of the project directory, then I can append the file name to the path. This can solve the issse
I maybe missing something obvious. In that case, please help me out.
Any suggestion gratefully accepted. Thanks in advance
Why do you think that res.sendFile(__dirname + "./sitemap.xml") would work?
First of all __dirname + "./sitemap.xml" is not how paths should be concatenated you should use join instead especially if your second path starts with ./. And there is no file sitemap.xml in the directory of the controller:
__dirname + "./sitemap.xml" would result in something like /path/to/project/src/controller/./sitemap.xml
And why should "../../sitemap.xml" work. If you only have "../../sitemap.xml" it is relative to the working directory which is the one where (i guess) index.js is located. So "../../sitemap.xml" will be resolved based on /path/to/project, so /path/to/project/../../sitemap.xml.
Due to that is either res.sendFile("./sitemap.xml") (relative to index.js) or res.sendFile(path.join(__dirname, "../../sitemap.xml")) (relative to the controller).

How do I access a JSON file relative to my calling module in Node?

I'm defining a package, PackageA, that has a function (parseJson) that takes in a file path to a json file to parse. In another package, PackageB, I want to be able to call PackageA using a file I specify with a local path from PackageB. For example, if file.json is in the same directory as packageB, I'd like to be able to call PackageA.parseJson('./file.json'), without any extra code in PackageB. How would I do this? It seems that require requires a path from PackageA to the file, which is not what I want.
Edit: Currently, parseJson looks something like this:
public parseJson(filepath) {
let j = require(filepath);
console.log(j);
}
and PackageB is calling it like this:
let a = new PackageA();
a.parseJson("./file.json");
file.json is in the same directory as PackageB.
CommonJS modules have __dirname variable in their scope, containing a path to directory they reside in.
To get absolute path to RELATIVE_PATH use join(__dirname, RELATIVE_PATH) (join from path module).
example:
// PackageB .js file
const Path = require('path')
const PackageA = require(/* PackageA name or path */)
const PackageB_jsonPathRelative = /* relative path to json file */
// __dirname is directory that contains PackageB .js file
const PackageB_jsonPathAbsolute = Path.join(__dirname, PackageB_jsonPathRelative)
PackageA.parseJson(PackageB_jsonPathAbsolute)
UPDATED
If you can't change PackageB, but you know exactly how PackageA.parseJson is called by PackageB (e.g. directly, or through wrappers, but with known depth), then you can get path to PackageB from stack-trace.
example:
// PackageA .js file
// `npm install stack-trace#0.0.10` if you have `ERR_REQUIRE_ESM` error
const StackTrace = require('stack-trace')
const Path = require('path')
const callerFilename = (skip=0) => StackTrace.get(callerFilename)[skip + 1].getFileName()
module.exports.parseJson = (caller_jsonPathRelative) => {
// we want direct caller of `parseJson` so `skip=0`
// adjust `skip` parameter if caller chain changes
const callerDir = Path.dirname(callerFilename())
// absolute path to json file, from relative to caller file
const jsonPath = Path.join(callerDir, caller_jsonPathRelative)
console.log(jsonPath)
console.log(JSON.parse(require('fs').readFileSync(jsonPath)))
}

How can i get the multiple .dat files in particular path in protractor

var filepath =../project/e2e/*.dat,
By using this I am able to get one file at a time but I need to fetch multiple files.
Instead of using this path to get the file, is there any other way to get multiple .dat files in the same path?
It will be better if you can share more details, like how are you fetching the files.
Though try this
const path = require('path'); //at global level
let filepath = '../project/e2e/*.dat';
let absolutePath = path.resolve(__dirname, filepath); // This will resolve the absolute path

Traverse '__dirname' in Node.js Application

I'm trying to get the parent of the current __dirname in my node application.
Here is my current line of code:
mu.root = __dirname + '/theme';
Yet, I want to reach out of the current directory and into another one of it's sibilings.
Here is my directory structure:
lib
this_file.js
theme
theme_file.file
How would I go about doing this without having to parse the result of __dirname?
You could use ../ to traverse to the parent of the current directory and path.join to resolve the path:
var path = require('path');
...
path.join(__dirname, "../whiceverdirectoryname");
Use path.dirname(__dirname)
Here's the doc.

fs: how do I locate a parent folder?

How do I write this to go back up the parent 2 levels to find a file?
fs.readFile(__dirname + 'foo.bar');
Try this:
fs.readFile(__dirname + '/../../foo.bar');
Note the forward slash at the beginning of the relative path.
Use path.join http://nodejs.org/docs/v0.4.10/api/path.html#path.join
var path = require("path"),
fs = require("fs");
fs.readFile(path.join(__dirname, '..', '..', 'foo.bar'));
path.join() will handle leading/trailing slashes for you and just do the right thing and you don't have to try to remember when trailing slashes exist and when they dont.
I know it is a bit picky, but all the answers so far are not quite right.
The point of path.join() is to eliminate the need for the caller to know which directory separator to use (making code platform agnostic).
Technically the correct answer would be something like:
var path = require("path");
fs.readFile(path.join(__dirname, '..', '..', 'foo.bar'));
I would have added this as a comment to Alex Wayne's answer but not enough rep yet!
EDIT: as per user1767586's observation
The easiest way would be to use path.resolve:
path.resolve(__dirname, '..', '..');
Looks like you'll need the path module. (path.normalize in particular)
var path = require("path"),
fs = require("fs");
fs.readFile(path.normalize(__dirname + "/../../foo.bar"));
If another module calls yours and you'd still like to know the location of the main file being run you can use a modification of #Jason's code:
var path = require('path'),
__parentDir = path.dirname(process.mainModule.filename);
fs.readFile(__parentDir + '/foo.bar');
That way you'll get the location of the script actually being run.
If you not positive on where the parent is, this will get you the path;
var path = require('path'),
__parentDir = path.dirname(module.parent.filename);
fs.readFile(__parentDir + '/foo.bar');
You can use
path.join(__dirname, '../..');
this will also work:
fs.readFile(`${__dirname}/../../foo.bar`);
i'm running electron app and i can get the parent folder by path.resolve()
parent 1 level:path.resolve(__dirname, '..') + '/'
parent 2 levels:path.resolve(__dirname, '..', '..') + '/'
This works fine
path.join(__dirname + '/../client/index.html')
const path = require('path')
const fs = require('fs')
fs.readFile(path.join(__dirname + '/../client/index.html'))
You can locate the file under parent folder in different ways,
const path = require('path');
const fs = require('fs');
// reads foo.bar file which is located in immediate parent folder.
fs.readFile(path.join(__dirname, '..', 'foo.bar');
// Method 1: reads foo.bar file which is located in 2 level back of the current folder.
path.join(__dirname, '..','..');
// Method 2: reads foo.bar file which is located in 2 level back of the current folder.
fs.readFile(path.normalize(__dirname + "/../../foo.bar"));
// Method 3: reads foo.bar file which is located in 2 level back of the current folder.
fs.readFile(__dirname + '/../../foo.bar');
// Method 4: reads foo.bar file which is located in 2 level back of the current folder.
fs.readFile(path.resolve(__dirname, '..', '..','foo.bar'));

Categories