F
F
faragly2015-09-04 09:21:06
gulp.js
faragly, 2015-09-04 09:21:06

How to turn a js object into a Gulp stream for further writing to a json file?

Hello! There is a js object, it needs to be written to a json file, how to implement it? I understand this is done using Vinyl

var json = {...};
file = new Vinyl({
                base: '/',
                path: 'file.json',
                contents: new Buffer(json)
            });

And then how to wrap it to crank it .pipe(gulp.dest('file.json'));?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Yarosh, 2015-09-04
@voidnugget

Gulp's streams are not node.js streams - they pass a file path and optionally its contents.
The easiest way is not to bother and do it through fs

var gulp = require('gulp'),
  g = require('gulp-load-plugins')(),
  fs = require('fs');

gulp.task('writeStuff', function(done) {
  var stuff = {};

  fs.writeFile('file.json', stuff, function(err) {
    if (err) throw err;
    g.util.log('It\'s saved!');
    done();
  });
});

Here is an example of how to create a file and push it to the stream:
var gutil = require('gulp-util'),
  through = require('through2');

function makeFileStream(name, source, options) {
  var file = new gutil.File({
    cwd: optaions.cwd | "",
    base: options.base | "",
    path: name,
    contents: ((source instanceof Buffer) ? source : new Buffer(source))
  });

  var stream = through.obj(function(file, enc, done) {
    this.push(file);
    return done();
  });

  stream.write(file);

  if (options && options.src) {
    stream.end();
  }

  return stream;
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question