2

I would like to add a new Vinyl file to the stream of a gulp task.

function task_add_vinyl_file(cb){
    const file = new Vinyl({
        cwd: '/',
        base: '/test/',
        path: '/test/file.js',
        contents: Buffer.from('var x = 123')
      });
    return gulp.src(
        [
            'path/to/files/**'
        ])
        .pipe(file)
        .pipe(gulp.dest('.'))
}

The problem is file is not compatible with .pipe()

How do you add a vinyl instance to the gulp pipe?

Arthur Weborg
  • 8,280
  • 5
  • 30
  • 67
chepe263
  • 2,774
  • 22
  • 38

1 Answers1

2

Before you start piping/consuming the stream produced from the gulp src function, you'll want to write the vinyl file object to the stream (in the following it's prepending the vinyl object(s), and that the stream created from src call will write data afterwards, once the stream starts consuming).

// create vinyl objects of interest
const file = new Vinyl({
    cwd: '/',
    base: '/test/',
    path: '/test/file.js',
    contents: Buffer.from('var x = 123')
  });

// the following initializes a stream, that we'll use to preppend the
// vinyl object.
let myStream = src(['path/to/files/**']);

// the following essentially pre-writes the vinyl object onto the stream
// note, this write can be done for multiple vinyl objects sequentially
myStream.write(file);

// and once we start piping, the stream consumes data until there
// is nothing else to consume, starting with the vinyl object
// and then moving onto the results of the glob in the src command.
myStream.pipe(gulp.dest('.'))

To understand more, I'd encourage anyone reading this to read up on nodejs streams.

Arthur Weborg
  • 8,280
  • 5
  • 30
  • 67