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?
pipe() method attaches a Writable stream to the readable, causing it to switch automatically into flowing mode and push all of its data to the attached Writable.
Gulp is a tool that helps you out with several tasks when it comes to web development. It's often used to do front end tasks like: Spinning up a web server. Reloading the browser automatically whenever a file is saved.
Gulp is a task runner that uses Node. js as a platform. Gulp purely uses the JavaScript code and helps to run front-end tasks and large-scale web applications. It builds system automated tasks like CSS and HTML minification, concatenating library files, and compiling the SASS files.
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/')) })
It's pretty much a one-liner in node:
require('fs').writeFileSync('dist/version.txt', '1.2.3');
Or from package.json:
var pkg = require('./package.json'); var fs = require('fs'); fs.writeFileSync('dist/version.txt', 'Version: ' + pkg.version);
I'm using it to specify a build date in an easily-accessible file, so I use this code before the usual return gulp.src(...)
in the build
task:
require('fs').writeFileSync('dist/build-date.txt', new Date());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With