[javascript] 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');

This question is related to javascript node.js filesystems

The answer is


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, '..', '..') + '/'


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 works fine

path.join(__dirname + '/../client/index.html')
const path = require('path')
const fs = require('fs')
    fs.readFile(path.join(__dirname + '/../client/index.html'))

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.


The easiest way would be to use path.resolve:

path.resolve(__dirname, '..', '..');

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


this will also work:

fs.readFile(`${__dirname}/../../foo.bar`);

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to filesystems

Get an image extension from an uploaded file in Laravel Notepad++ cached files location No space left on device How to create a directory using Ansible best way to get folder and file list in Javascript Exploring Docker container's file system Remove directory which is not empty GIT_DISCOVERY_ACROSS_FILESYSTEM not set Trying to create a file in Android: open failed: EROFS (Read-only file system) Node.js check if path is file or directory