Skip to content

Instantly share code, notes, and snippets.

@ddprrt
Created October 29, 2015 21:21
Show Gist options
  • Save ddprrt/ee51248ff3e4eeda3d33 to your computer and use it in GitHub Desktop.
Save ddprrt/ee51248ff3e4eeda3d33 to your computer and use it in GitHub Desktop.
Gulp task system and Promises
/**
* Bluebird allows us to promisify existing Node.js
* technologies. So fs.writeFile and fs.readFile
* are usable with Promises.
*
* `fetch` fetches Ressources. This code fetches
* jQuery, and saves the responses body in a file
**/
var gulp = require('gulp');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var fetch = require('node-fetch');
gulp.task('fetch', function() {
return fetch('http://code.jquery.com/jquery-2.1.4.min.js')
.then(function(data) {
return data.text();
})
.then(function(body) {
return fs.writeFileAsync('jquery.js', body);
});
});
@fhemberger
Copy link

When using Node.js 4, you can also use arrow functions:

  return fetch('http://code.jquery.com/jquery-2.1.4.min.js')
    .then(data => data.text())
    .then(body => fs.writeFileAsync('jquery.js', body));

Even better, use streams instead:

const fs = require('fs');
const http = require('http');

http.get('http://code.jquery.com/jquery-2.1.4.min.js', function (res) {
    res.pipe(fs.createWriteStream('jquery.js'));
});

@ddprrt
Copy link
Author

ddprrt commented Oct 30, 2015

Cool :-) I'm still new to all the Node 4 stuff ;-) With streams, I'd use the gulp API then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment