gulpjs / vinyl

Virtual file format.
MIT License
1.28k stars 105 forks source link

Reading a file into a vinyl #20

Closed adam-lynch closed 10 years ago

adam-lynch commented 10 years ago

What's the best way of instantiating a vinyl based on a file on disk. I looked at vinyl-fs but I don't think it's what I'm looking for. Maybe I'm being stupid / missing something but in some tests for my gulp plugins, I do stuff like:

new Vinyl({
//...
    contents: fs.readFileSync('./fixtures/test.xml');
});

What I'm for is something that I can pass a path to and get a new Vinyl in return.

yocontra commented 10 years ago
var vfs = require('vinyl-fs');
var nextback = require('nextback');

var getFiles = function(path, cb) {
  cb = nextback(cb);
  var files = [];
  var globber = vfs.src(path);
  globber.once('error', cb);
  globber.on('data', function(file){
    files.push(file);
  });
  globber.once('end', function(){
    cb(null, files);
  });
};
getFiles('./fixtures/test.xml', function(err, files){
  var file = files[0];
  // do your test here
});
getFiles('./fixtures/*.xml', function(err, files){
  // do your test here
});

If you use mocha this is easy to add in a before/beforeEach section and then assign the files to this.fixtures or something. You can synchronously create a vinyl file but you'll have to create those variables and pass them to the Vinyl constructor yourself (fs.readFileSync, fs.lstatSync, etc.)

adam-lynch commented 10 years ago

Thanks. I was thinking without globs, but I guess it makes things easier in some cases.