Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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?

like image 728
Daryl Avatar asked Apr 22 '14 21:04

Daryl


People also ask

What does pipe do in Gulp?

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.

What is a Gulp file?

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.

What was used by the Gulp files?

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.


2 Answers

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/')) }) 
like image 186
Christoph Neumann Avatar answered Sep 29 '22 15:09

Christoph Neumann


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()); 
like image 38
fregante Avatar answered Sep 29 '22 15:09

fregante