Gulp: insert content from file into script - gulp

I've a JavaScript file script.js like this:
var myArray = {"INSERT":"ARRAY"};
Further I've a array.json file like this:
{
"Item1": "Text1",
"Item2": "Text2"
}
I would like gulp to replace the array in the script.js with the content in the array.json file. How can I do that?
I've been looking at gulp-replace and have this example:
gulp.task('my-task', [], function () {
return gulp.src(['script.js'])
.pipe(replace('{"INSERT":"ARRAY"}', '{"MY":"OTHER_ARRAY"}'))
.pipe(gulp.dest("dist.js"));
});
where I successfully replace the text, but instead of replacing with a static array, I need to read the array.json file instead and use this instead. I'm not sure how I can do that or if there are any better solutions to this? I've been looking at gulp-inject, but I'm not sure if this can be used in my case?

Just read the file contents?
gulp.task('my-task', [], function () {
var replacement = fs.readFileSync('path/to/file');
return gulp.src(['script.js'])
.pipe(replace('{"INSERT":"ARRAY"}', replacement))
.pipe(gulp.dest("dist.js"));
});

Related

Get current file name in Gulp Stream

I've read Get the current file name in gulp.src(), and it seems like it's approaching what I am attempting to do, but I need help.
Consider the following function in a gulpfile.js:
function inline() {
return gulp.src('dist/**/*.html')
.pipe($.if(PRODUCTION, inliner('dist/css/app.css')))
.pipe(gulp.dest('dist'));
}
And inliner(), to be thorough (also in the gulpfile):
function inliner(css) {
var css = fs.readFileSync(css).toString();
var mqCss = siphon(css);
var pipe = lazypipe()
.pipe($.inlineCss, {
applyStyleTags: false,
removeStyleTags: false,
removeLinkTags: false
})
.pipe($.replace, '<!-- <style> -->', `<style>${mqCss}</style>`);
return pipe();
}
These functions take an external CSS file and inline them into the respective HTML for email.
I really want to know how to do something like this:
function inline() {
return gulp.src('dist/**/*.html')
.pipe($.if(PRODUCTION, inliner('dist/css/' + file.name + '.css')))
.pipe(gulp.dest('dist'));
}
And you might ask yourself, "why?" Well, I don't have just one CSS file. If everything from app.css was to be inlined, there would be a lot more styles applied than were actually necessary.
So I want to inline:
email1.css ---- to -------> email1.html
email2.css ---- to -------> email2.html
email3.css ---- to -------> email3.html
And so on. Essentially, I want to get the name of the HTML file being processed at that moment in the Gulp Stream, save it as a variable, and then pass it into the inliner('dist/css/' + file.name + '.css') bit. I've exhausted every bit of Gulp Knowledge I have and have come up completely and utterly blank.
Basically what you need to do is send each .html file in your stream down its own little sub stream with its own inliner(). The gulp-foreach plugin let's you do just that.
Then it's just a matter of determining the simple name of your file from its absolute path. The node.js built-in path.parse() got you covered there.
Putting it all together:
var path = require('path');
function inline() {
return gulp.src('dist/**/*.html')
.pipe($.if(PRODUCTION, $.foreach(function(stream, file) {
var name = path.parse(file.path).name;
return stream.pipe(inliner('dist/css/' + name + '.css'));
})))
.pipe(gulp.dest('dist'));
}

Gulp: replace variables in HTML file based on file name

Our project is using Gulp. Now I have a requirement: we have multiple page-level HTML files, say login.html and my.html. Inside these original HTML files there is a variable called {{PAGE_TITLE}}, which should be replaced (by Gulp) to be "Login to System" and "My Account" respectively. Here is my current script:
gulp.task('pages', ['clean:tmp'], function () {
var pageTitle = '';
return gulp.src('/my/source/html/**/*.html')
.pipe(tap(function (file, t) {
pageTitle = /index.html$/.test(file.path) ? 'Login to System' : 'My Account';
}))
.pipe(replace(/{{PAGE_TITLE}}/g, pageTitle))
.pipe(gulp.dest('/my/dest/'));
});
It turns out the variable pageTitle is never set before the replace. I have searched for documentation of gulp-tap for tons of times, but I still do not know how to make it work. Please help, thanks.
This post: Modify file in place (same dest) using Gulp.js and a globbing pattern tries to achieve the same affect, but he resulted in some other solution.
I figured out the solution as followed:
gulp.task('pages', ['clean:tmp'], function () {
function replaceDynamicVariables(file) {
var pageTitle = /login.html$/.test(file.path) ? 'Login to System' : 'My Account';
file.contents = new Buffer(String(file.contents)
.replace(/{{PAGE_TITLE}}/, pageTitle)
);
}
return gulp.src('/my/source/html/**/*.html')
.pipe(tap(replaceDynamicVariables))
.pipe(gulp.dest('/my/dest/'));
});

Get the current file name in gulp.src()

In my gulp.js file I'm streaming all HTML files from the examples folder into the build folder.
To create the gulp task is not difficult:
var gulp = require('gulp');
gulp.task('examples', function() {
return gulp.src('./examples/*.html')
.pipe(gulp.dest('./build'));
});
But I can't figure out how retrieve the file names found (and processed) in the task, or I can't find the right plugin.
I'm not sure how you want to use the file names, but one of these should help:
If you just want to see the names, you can use something like gulp-debug, which lists the details of the vinyl file. Insert this anywhere you want a list, like so:
var gulp = require('gulp'),
debug = require('gulp-debug');
gulp.task('examples', function() {
return gulp.src('./examples/*.html')
.pipe(debug())
.pipe(gulp.dest('./build'));
});
Another option is gulp-filelog, which I haven't used, but sounds similar (it might be a bit cleaner).
Another options is gulp-filesize, which outputs both the file and it's size.
If you want more control, you can use something like gulp-tap, which lets you provide your own function and look at the files in the pipe.
I found this plugin to be doing what I was expecting: gulp-using
Simple usage example: Search all files in project with .jsx extension
gulp.task('reactify', function(){
gulp.src(['../**/*.jsx'])
.pipe(using({}));
....
});
Output:
[gulp] Using gulpfile /app/build/gulpfile.js
[gulp] Starting 'reactify'...
[gulp] Finished 'reactify' after 2.92 ms
[gulp] Using file /app/staging/web/content/view/logon.jsx
[gulp] Using file /app/staging/web/content/view/components/rauth.jsx
Here is another simple way.
var es, log, logFile;
es = require('event-stream');
log = require('gulp-util').log;
logFile = function(es) {
return es.map(function(file, cb) {
log(file.path);
return cb(null, file);
});
};
gulp.task("do", function() {
return gulp.src('./examples/*.html')
.pipe(logFile(es))
.pipe(gulp.dest('./build'));
});
You can use the gulp-filenames module to get the array of paths.
You can even group them by namespaces:
var filenames = require("gulp-filenames");
gulp.src("./src/*.coffee")
.pipe(filenames("coffeescript"))
.pipe(gulp.dest("./dist"));
gulp.src("./src/*.js")
.pipe(filenames("javascript"))
.pipe(gulp.dest("./dist"));
filenames.get("coffeescript") // ["a.coffee","b.coffee"]
// Do Something With it
For my case gulp-ignore was perfect.
As option you may pass a function there:
function condition(file) {
// do whatever with file.path
// return boolean true if needed to exclude file
}
And the task would look like this:
var gulpIgnore = require('gulp-ignore');
gulp.task('task', function() {
gulp.src('./**/*.js')
.pipe(gulpIgnore.exclude(condition))
.pipe(gulp.dest('./dist/'));
});
If you want to use #OverZealous' answer (https://stackoverflow.com/a/21806974/1019307) in Typescript, you need to import instead of require:
import * as debug from 'gulp-debug';
...
return gulp.src('./examples/*.html')
.pipe(debug({title: 'example src:'}))
.pipe(gulp.dest('./build'));
(I also added a title).

CasperJs loads json data from a local file

Is there any convenient way to load a local JSON file into a variable with CasperJs?
I saw someone suggest to use
$.getJSON(filename, function() ...
I have the following working on CasperJS 1.1-beta1 and PhantomJS 1.9.1
test.json
{
"test": "hello"
}
test.js
var json = require('test.json');
require('utils').dump(json);
casper.echo(json.test); // "hello"
The solution proposed by #hexid worked for me with one change, i added a './' before the file address to denote it is a local file.
test.json
{
"test": "hello"
}
test.js
var utils = require('utils');
var json = require('./test.json');
utils.dump(json);
utils.dump(json.test); // hello
utils.dump(json["test"]); // hello
(i would add it as a comment but I'd need 50+ rep to do that)
Here is a complete sample
var casper = require('casper').create();
var json = require('test.json');
require('utils').dump(json);
casper.echo(json['test']);
casper.exit();

trying to understand jsonp with the flickr example

I'm trying to get my head around how I can make json request to a json file stored on my server from jsfiddle.
html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="images">
</div>
</body>
</html>
jquery:
$.getJSON("http://www.shopsheep.com/groupon/json/test.json?jsoncallback=?", function(data) {
$.each(data.items, function(i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 0) {
return false;
}
});
});
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?", function(data) {
$.each(data.items, function(i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 0) return false;
});
});
I downloaded the flicker json file and uploaded it to my server as test.json. If I paste it in the browser it returns just as the flicker file.
However when I try to display the image only the original flicker example is working? Any idea why this is the case?
http://jsfiddle.net/stofke/DJQ5g
Ok I have found out how to do this. The getJSON function adds a random
named callback functionname to jsoncallback=? something like this
jQuery160188050875203142_1309437718540&_=1309437718551
In order to wrap your json file with this callbackfunction you need of course to know the name of this function, so if you convert your jsonfile into a php file than you can get the callbackfunctionname like this:
<?php echo $_GET["jsoncallback"];?>(
ADD JSON CONTENT HERE
)
This php file will get the name of the callbackfunction via a GET variable and wraps the json content with it. This way it works fine.
Your JSON file missed function name. It should start with function name.
If you see here http://api.flickr.com/services/feeds/photos_public.gne?format=json, it starts with jsonFlickrFeed.
Your JSON should be like this:
callback({
"title": "Uploads from everyone",
"link": "http://www.flickr.com/photos/",
"description": "",
"modified": "2011-06-29T21:43:16Z",
"generator": "http://www.flickr.com/",
"items": [
{....
Maybe you need to understand more about JSONP. http://en.wikipedia.org/wiki/JSONP