Get parent directory name in Node.js

前端 未结 8 1490
北海茫月
北海茫月 2021-01-31 13:27

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

相关标签:
8条回答
  • 2021-01-31 13:41

    What you want is path.basename:

    path.basename(path.dirname(filename))
    
    0 讨论(0)
  • 2021-01-31 13:41

    Daniel Wolf's answer is correct, also if you want the full path of the parent dir:

    require('path').resolve(__dirname, '..')
    
    0 讨论(0)
  • 2021-01-31 13:47

    Simplest way without any node modules like the path. You can easily do in the following manner to get the root folder name.

    var rootFolder = __dirname.split('/').pop();
    console.log(rootFolder);
    
    0 讨论(0)
  • 2021-01-31 13:48
    const path = require('path');
    
    module.exports = path.dirname(process.mainModule.filename)
    

    Use this anywhere to get the root directory

    0 讨论(0)
  • 2021-01-31 13:56

    process.mainModule property is deprecated in v14.0.0. If foo.js is run by node foo.js (e.g. somedir/foo.js"),

    const path = require("path");
    
    module.exports = path.dirname(require.main.filename);
    

    result: somedir

    Use require.main instead

    0 讨论(0)
  • 2021-01-31 13:58

    Using node as of 06-2019, I ran into an issue for accessing just filename. So instead, I just modified it a tiny bit and used:

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

    so now you get the directory name of the current directory you are in and not the full path. Although the previous answers seem to possibly work for others, for me it caused issues as node was looking for a const or a variable but couldn't find one.

    0 讨论(0)
提交回复
热议问题