136

Is there a way to get the path to a folder that holds a particular file.

fs.realpathSync('config.json', []);

returns something like

G:\node-demos\7-node-module\demo\config.json

I just need

G:\node-demos\7-node-module\demo\ 
or
G:\node-demos\7-node-module\demo\

Is there any api for this or will I need to process the string?

blessanm86
  • 31,439
  • 14
  • 68
  • 79

3 Answers3

230

use path.dirname

// onlyPath should be G:\node-demos\7-handlebars-watch\demo
var onlyPath = require('path').dirname('G:\\node-demos\\7-node-module\\demo\\config.json');
David Murdoch
  • 87,823
  • 39
  • 148
  • 191
hereandnow78
  • 14,094
  • 8
  • 42
  • 48
  • 2
    Double your backslashes, or you’ll end up escaping random characters. – Константин Ван Jul 20 '19 at 16:05
  • 1
    if you're starting with a relative path like in the original question, you would do- `let onlyPath = path.dirname(fs.realpathSync('config.json'));` – Kip Dec 05 '19 at 15:53
  • I would want to always use @Kip method of using `realpathSync` which covers absolute and relative paths – joshweir Mar 05 '20 at 23:32
  • Just to add a warning on this. If your path doesn't have a file name on the end (i.e your using the same code for multiple things) it will just strip off the last directory in your path instead. It's a dumb function which works well if you're 100% sure the file path has a file in it. – webnoob May 26 '21 at 06:38
  • @webnoob You could see it as it being dumb, or you could see it as it giving the directory that contains that directory. It's not wrong. That "dumb" behaviour is exactly what you want. Did you want it to be impossible to get the name of the directory that contains a directory? – doug65536 Feb 28 '23 at 22:12
  • @doug65536 I don't mean dumb in terms of "stupid", I mean it in programming terms of having one job and doing only that one job with the fixed data sent in. It won't make life easy for you :) – webnoob Mar 09 '23 at 08:27
18

Simply install path module and use it,

var path = require('path');
path.dirname('G:\\node-demos\\7-node-module\\demo\\config.json')

// Returns: 'G:\node-demos\7-node-module\demo'
Community
  • 1
  • 1
Subhashi
  • 4,145
  • 1
  • 23
  • 22
6

require("path").dirname(……) breaks when your path does not explicitly specify its directory.

require("path").dirname("./..")
// "."

You may consider using require("path").join(……, "../") instead. It preserves the trailing separator as well.

require("path").join("whatever/absolute/or/relative", "../")
// "whatever/absolute/or/" (POSIX)
// "whatever\\absolute\\or\\" (Windows)
require("path").join(".", "../")
// "../" (POSIX)
// "..\\" (Windows)
require("path").join("..", "../")
// "../../" (POSIX)
// "..\\..\\" (Windows)
require("path").win32.join("C:\\", "../")
// "C:\\"