Let's say I have a file at /Users/me/app/src/scripts/foo.js
. I set up a gulp tasks that writes this file to /Users/me/app/dist/scripts/foo.js
:
gulp.src('src/scripts/foo.js', base: 'src')
.pipe(...)
.pipe(gulp.dest('dist'))
I'm writing a simple plugin and need to know scripts/foo.js
. I was expecting file.relative
to be this partial path, but instead it provides foo.js
. I don't see a way to get scripts/foo.js
from any combination of file.path
, file.cwd
, file.base
, etc.
How can I get the part of the path I need?
Assuming that you want the path relative to your specified base, you would want to use something like node's path module to do the extraction:
var path = require('path');
// this is how you get the relative path from a vinyl file instance
path.relative(path.join(file.cwd, file.base), file.path);
Here is an example gulpfile using your example:
var path = require('path'),
gulp = require('gulp'),
through = require('through2');
function parsePath() {
return through.obj(function (file, enc, cb) {
console.log(file.base);
console.log(file.cwd);
console.log(file.path);
console.log(path.relative(path.join(file.cwd, file.base), file.path))
cb();
});
}
gulp.task('default', function () {
gulp.src('src/scripts/foo.js', { base: 'src'})
.pipe(parsePath())
.pipe(gulp.dest('dist'));
});
Here is the output when I run this gulpfile:
src
/Volumes/Data/Project/sandbox/gulp-ex
/Volumes/Data/Project/sandbox/gulp-ex/src/scripts/foo.js
scripts/foo.js
Here is the project folder structure
gulp-ex/
|_ gulpfile.js
|_ src/scripts/foo.js
|_ dist