Search code examples
node.jspath

Get parent directory name in Node.js


I am using Node.js, and I want to obtain the parent directory name for a file. I have the file "../test1/folder1/FolderIWant/test.txt".

I want to get "FolderIWant".

I have tried:

var path = require('path');
var parentDir = path.dirname(filename);

But it returns ../test1/folder1/FolderIWant.


Solution

  • Better use @danielwolf's answer instead


    Use split() and pop():

    path.dirname(filename).split(path.sep).pop()