Splice path with Gulp-data

256 views Asked by At

How do I get the name of the parent folder using gulp-data? Currently I'm using the following:

In my front matter

---
title: 'some title'
----

from my gulp file:

function fm2json() {
  return gulp.src('src/pages/**/*.html')
    .pipe(require('gulp-gray-matter')())
    .pipe($.data(function(file){
      file.data.relative = file.relative,
      file.data.basename = file.basename,
    }))
    .pipe($.pluck('data', 'new.json'))
    .pipe($.data(function(file){
      file.contents = new Buffer(JSON.stringify(file.data))
    }))
    .pipe(require('gulp-json-format')(2))
    .pipe(gulp.dest('src/data'));
}

which outputs the following to new.json

[
  {
    "title":"some title" 
    "relative":"lesson01\\file.html" 
    "basename":"file.html" 
  },
  {
    "title":"some title 2" 
    "relative":"lesson02\\file2.html" 
    "basename":"file2.html" 
  }
]

I can't figure out how to just get the parent folder of the file so that relative would be "relative":"lesson01" and "relative":"lesson02".

1

There are 1 answers

0
AudioBubble On

It's not the most efficient way to do it. If it helps anyone this is what I ended up with.

function fm2json() {
  return gulp.src('src/pages/**/*.html')
    .pipe(require('gulp-gray-matter')())
    .pipe($.data(function(file){

        // What I ended up with
        var relpath = file.relative;
        var path    = relpath.replace(/\\/g,"/"); //flip slashes
        var split   = path.split('/'); //split the path into an array
        var parent  = split[split.length - 2]; // find the array position

        file.data.parent = parent,
        file.data.file   = file.basename,
        file.data.path   = path,

    }))
    .pipe($.pluck('data', 'new.json'))
    .pipe($.data(function(file){
      file.contents = new Buffer(JSON.stringify(file.data))
    }))
    .pipe(require('gulp-json-format')(2))
    .pipe(gulp.dest('src/data'));
}