Node js Get folder path from a file
use path.dirname
// onlyPath should be G:\node-demos\7-handlebars-watch\demovar onlyPath = require('path').dirname('G:\\node-demos\\7-node-module\\demo\\config.json');
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'
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:\\"