144

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?

2 Answers 2

240

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');
Sign up to request clarification or add additional context in comments.

6 Comments

Double your backslashes, or you’ll end up escaping random characters.
if you're starting with a relative path like in the original question, you would do- let onlyPath = path.dirname(fs.realpathSync('config.json'));
I would want to always use @Kip method of using realpathSync which covers absolute and relative paths
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 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?
|
7

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:\\"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.