Geraud Schmit
Geraud Schmit

Reputation: 35

gulp-exec : how to inject dest files in the command based on source files

I have written a gulp task to generate pdf files based on source files written in markdown format (using the gulp-exec plugin and a command line tool called Pandoc).

My task looks like this:

gulp.task('pandoc', function() {
  var options = {
    continueOnError: false,
    pipeStdout: false
  };
  var reportOptions = {
    err: true,
    stderr: true,
    stdout: true
  };
  gulp.src('./pandoc/**/*.md')
    .pipe(gulpexec('pandoc -f markdown -t latex -s <%= file.path %> -o pandoc/test/<%= file.relative %>.pdf', options))
    .pipe(gulpexec.reporter(reportOptions));
});

It works perfectly except that the dest files have this format: "filename.md.pdf" (if the source file is "filename.md"). That's because I use <%= file.relative %> in the exec command which actually stores the name of the source file ("filename.md").

Would it be possible to have the dest files written like this: "filename.pdf" ? I tried to use <%= file.basename %> instead of <%= file.relative %> but it doesn't work. Of course, I could create another task and rewrite all the files but I would like to find a more elegant way. Any idea ?

Thanks

Upvotes: 1

Views: 453

Answers (1)

Timothy Meade
Timothy Meade

Reputation: 2516

You can create a function to generate the desired filename and inject it through the opt parameter on gulp-exec:

var gulpexec = require('gulp-exec');
var path = require('path');

gulp.task('pandoc', function() {
  var options = {
    continueOnError: false,
    pipeStdout: false
  };
  var reportOptions = {
    err: true,
    stderr: true,
    stdout: true
  };

  var outDir = './pandoc/test/';

  function execPandoc(outDir, options) {
    options = options || {};

    options._out = function(file) {
      return path.join(outDir, path.basename(file.relative, path.extname(file.relative)));
    };

    // Output an object to pipe into
    return gulpexec('pandoc -f markdown -t latex -s <%= file.path %> -o <%= options._out(file) %>.pdf', options)
  };

  gulp.src('./pandoc/**/*.md')
    .pipe(execPandoc(outDir, options))
    .pipe(gulpexec.reporter(reportOptions));
});

Upvotes: 0

Related Questions