Node js Get folder path from a file

node.jsCommand Line-InterfaceNpm

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

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');

Solution 2 - node.js

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'

Solution 3 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionblessanm86View Question on Stackoverflow
Solution 1 - node.jshereandnow78View Answer on Stackoverflow
Solution 2 - node.jsSubhashiView Answer on Stackoverflow
Solution 3 - node.jsКонстантин ВанView Answer on Stackoverflow