Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js Get folder path from a file

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?

like image 439
blessanm86 Avatar asked Jun 19 '13 13:06

blessanm86


People also ask

How do I find the path of a NodeJS file?

We can get the path of the present script in node. js by using __dirname and __filename module scope variables. __dirname: It returns the directory name of the current module in which the current script is located. __filename: It returns the file name of the current module.

How do I write a file path in NodeJS?

js: var fs = require('fs') var newPath = "E:\\Thevan"; var oldPath = "E:\\Thevan\\Docs\\something. mp4"; exports. uploadFile = function (req, res) { fs. readFile(oldPath, function(err, data) { fs.

What is __ Dirname in NodeJS?

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file. Difference between process.cwd() vs __dirname in Node.js is as follows: process.cwd()

How do I get cwd in JavaScript?

In Node. js, there are two built-in ways to get the current directory. You can either use the __dirname variable or the process. cwd() method to get the current folder.


1 Answers

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'); 
like image 135
hereandnow78 Avatar answered Oct 17 '22 12:10

hereandnow78