node.jsgulp

How do you create a file from a string in Gulp?


In my gulpfile I have a version number in a string. I'd like to write the version number to a file. Is there a nice way to do this in Gulp, or should I be looking at more general NodeJS APIs?


Solution

  • If you'd like to do this in a gulp-like way, you can create a stream of "fake" vinyl files and call pipe per usual. Here's a function for creating the stream. "stream" is a core module, so you don't need to install anything:

    const Vinyl = require('vinyl')
    
    function string_src(filename, string) {
      var src = require('stream').Readable({ objectMode: true })
      src._read = function () {
        this.push(new Vinyl({
          cwd: "",
          base: "",
          path: filename,
          contents: Buffer.from(string, 'utf-8')
        }))
        this.push(null)
      }
      return src
    }
    

    You can use it like this:

    gulp.task('version', function () {
      var pkg = require('package.json')
      return string_src("version", pkg.version)
        .pipe(gulp.dest('build/'))
    })