Search code examples
node.jsgulp

Get grandparent directory name in gulp


I'm tying to get get the grandparentparent directory of my gulpfile.js file. This is my folder structure : airi\Gulp\gulpfile.js I want to get the folder with name airi.

gulp.task('serve', ['sass'], function () {
    browserSync.init({
        proxy: "http://localhost/" + var_that_stores_name_airi,
    });
});

var_that_stores_name_airi would be my variable that contains the folder name I want ( ie: airi ).I want this so that I can append it my browsersync proxy url. How do I do this in gulp ? Thanks


Solution

  • If you want to be fancy, this will do it:

    const path = require('path');
    
    let dir = path.relative(path.parse(path.dirname(__dirname)).dir, path.parse(__dirname).dir)
    

    or try the simpler

    let dir = path.parse(path.resolve(__dirname, '../')).name;
    

    [Thanks to @DerekNguyen's excellent comment below.]

    This will also do it:

    const path = require('path');
    
    let dir = __dirname.split(path.sep);
    dir = dir[dir.length - 2];
    console.log("dir = " + dir);
    
    
    gulp.task('serve', ['sass'], function () {
    
      let dir = __dirname.split(path.sep);
      dir = dir[dir.length - 2];
    
      browserSync.init({
        proxy: "http://localhost/" + dir,
      });
    });