livereload - Image is not resize immediately after uploading - node.js

I have created gulp tasks scheduler for JavaScript minification and image resizing. All things work nicely when I executes command manually.
Command:
gulp
But when I include gulp-livereload module to perform operation automatically, Command line watch continuously when I upload images, it does not resize.
Just cursor is blinking. When uploads an image, no activities display in command watch list.
gulpfile.js
// include gulp
var gulp = require('gulp');
// include plug-ins
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var stripDebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var imageresize = require('gulp-image-resize');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
var liveReload = require("gulp-livereload");
// JS hint task
gulp.task('jshint', function () {
gulp.src([
'./app/client/app.js',
'./app/client/app.routes.js',
'./app/client/modules/**/controllers/*.js',
'./app/client/modules/**/directives/*.js',
'./app/client/modules/**/services/*.js',
'./app/client/services/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(liveReload());
});
gulp.task('jsminification', function () {
gulp.src([
'./app/client/app.js',
'./app/client/app.routes.js',
'./app/client/modules/**/controllers/*.js',
'./app/client/modules/**/directives/*.js',
'./app/client/modules/**/services/*.js',
'./app/client/modules/**/filter/*.js',
'./app/client/services/*.js'])
.pipe(concat('script.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./app/build/scripts/'))
.pipe(liveReload());
});
gulp.task('resize', function () {
// set the folder name and the relative paths
// in the example the images are in ./assets/images
// and the public directory is ../public
var paths = {
folder: 'media/',
src: './app/client/',
dest: './app/client/resize/'
};
// create an array of image groups (see comments above)
// specifying the folder name, the ouput dimensions and
// whether or not to crop the images
var images = [
// {folder: 'bg', width: 1200, crop: false},
{folder: 'photo', width: 120, height: 120, crop: true},
//{folder: 'projects', width: 800, height: 500, crop: true}
];
console.log("resize called");
// loop through image groups
images.forEach(function (type) {
console.log(type);
var source_ = paths.src + paths.folder + type.folder + '/*';
var scale_ = type.width + "x" + type.height + "/";
//var destination_ = paths.dest + paths.folder + scale_ + type.folder;
var destination_ = paths.dest + scale_ + type.folder;
console.log(">source:" + source_);
console.log(">scale:" + scale_);
console.log(">destination:" + destination_);
// build the resize object
var resize_settings = {
width: type.width,
crop: type.crop,
// never increase image dimensions
upscale: false
}
// only specify the height if it exists
if (type.hasOwnProperty("height")) {
resize_settings.height = type.height;
}
gulp
// grab all images from the folder
.src(source_)
// resize them according to the width/height settings
.pipe(imageresize(resize_settings))
// output each image to the dest path
// maintaining the folder structure
.pipe(gulp.dest(destination_))
.pipe(liveReload());
});
});
gulp.task('watch', function () {
liveReload.listen({host: process.env['HOST'], port: process.env['PORT']});
gulp.watch('./app/client/media/photo/*.{png,jpg,jpeg}', ['resize']);
});
gulp.task('default', ['jshint', 'jsminification', 'resize', 'watch']);
I want to resize image automatically as new image uploads in photo folder.

After some R&D I have found following solution using "gulp-watch" module and it works fine.
// include gulp
var gulp = require('gulp');
// include plug-ins
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var stripDebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var imageresize = require('gulp-image-resize');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
var watch = require("gulp-watch");
var newer = require("gulp-newer");
var paths = {
folder: 'media/',
src: './app/client/',
dest: './app/client/resize/'
}
var images = [
{folder: 'photo', width: 120, height: 120, crop: true},
];
// JS hint task
gulp.task('jshint', function () {
gulp.src([
'./app/client/app.js',
'./app/client/app.routes.js',
'./app/client/modules/**/controllers/*.js',
'./app/client/modules/**/directives/*.js',
'./app/client/modules/**/services/*.js',
'./app/client/services/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// JS minification task
gulp.task('jsminification', function () {
gulp.src([
'./app/client/app.js',
'./app/client/app.routes.js',
'./app/client/modules/**/controllers/*.js',
'./app/client/modules/**/directives/*.js',
'./app/client/modules/**/services/*.js',
'./app/client/modules/**/filter/*.js',
'./app/client/services/*.js'])
.pipe(concat('script.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./app/build/scripts/'));
});
// image resize
gulp.task('resize', function () {
// loop through image groups
images.forEach(function (type) {
var source_ = paths.src + paths.folder + type.folder + '/*';
var scale_ = type.width + "x" + type.height + "/";
//var destination_ = paths.dest + paths.folder + scale_ + type.folder;
var destination_ = paths.dest + scale_ + type.folder;
// build the resize object
var resize_settings = {
width: type.width,
crop: type.crop,
// never increase image dimensions
upscale: false
}
// only specify the height if it exists
if (type.hasOwnProperty("height")) {
resize_settings.height = type.height;
}
gulp
// grab all images from the folder
.src(source_)
.pipe(newer(destination_))
// resize them according to the width/height settings
.pipe(imageresize(resize_settings))
// optimize the images
.pipe(imagemin({
progressive: true,
// set this if you are using svg images
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
// output each image to the dest path
// maintaining the folder structure
.pipe(gulp.dest(destination_));
});
});
// Gulp default task
gulp.task('default', ['jshint', 'jsminification', 'resize'], function () {});
// Gulp watch for new image resizing
watch('./app/client/media/photo/*.+(png|jpg|jpeg|gif)', function () {
gulp.run('resize');
});

Related

Gulp 4.0 version problem - parallel is not a function

I need help with my gulp project. Drops me error in terminal: TypeError: parallel is not a function Already searched information whole internet. Answer is to update Gulp version to 4.0.. Already updated. still shows the "parallel function" issue
My file:
const { src, dest, parallel, series, watch } = import('gulp');
const twig = import('gulp-twig');
const sass = import('gulp-sass');
const prefix = import('gulp-autoprefixer');
const data = import('gulp-data');
const sourcemaps = import('gulp-sourcemaps');
const concat = import('gulp-concat');
const plumber = import('gulp-plumber');
const browsersync = import('browser-sync');
const gulpcopy = import('gulp-copy');
const fs = import('fs');
const del = import('del');
const path = import('path');
var paths = {
build: {
html: 'dist/',
js: 'dist/assets/js/',
css: 'dist/assets/css/',
img: 'dist/assets/img/',
fonts: 'dist/assets/fonts/',
icons: 'dist/assets/icons/',
json: 'dist/assets/'
},
src: {
html: 'src/*.{htm,html,php}',
js: 'src/assets/js/*.js',
css: 'src/assets/sass/style.scss',
img: 'src/assets/img/**/*.*',
fonts: 'src/assets/fonts/**/*.*',
icons: 'src/assets/icons/**/*.*',
json: 'src/assets/*.json'
},
watch: {
html: 'src/**/*.{htm,html,php}',
js: 'src/assets/js/**/*.js',
css: 'src/assets/sass/**/*.scss',
img: 'src/assets/img/**/*.*',
fonts: 'src/assets/fonts/**/*.*',
icons: 'src/assets/icons/**/*.*',
json: 'src/assets/*.json'
},
clean: './dist'
};
// SCSS bundled into CSS task
function css() {
return src('client/scss/vendors/*.scss')
.pipe(sourcemaps.init())
// Stay live and reload on error
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(sass({
includePaths: [paths.src.css + 'vendors/'],
outputStyle: 'compressed'
}).on('error', function (err) {
console.log(err.message);
// sass.logError
this.emit('end');
}))
.pipe(prefix(['last 15 versions','> 1%','ie 8','ie 7','iOS >= 9','Safari >= 9','Android >= 4.4','Opera >= 30'], {
cascade: true
}))
//.pipe(minifyCSS())
.pipe(concat('bootstrap.min.css'))
.pipe(sourcemaps.write('.'))
.pipe(dest('build/assets/css'));
}
// JS bundled into min.js task
function js() {
return src('dist/js/*.js')
.pipe(sourcemaps.init())
.pipe(concat('scripts.min.js'))
.pipe(sourcemaps.write('.'))
.pipe(dest('build/assets/js'));
}
function twigTpl () {
return src(['./dist/templates/*.twig'])
// Stay live and reload on error
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
// Load template pages json data
.pipe(data(function (file) {
return JSON.parse(fs.readFileSync(paths.data + path.basename(file.path) + '.json'));
}).on('error', function (err) {
process.stderr.write(err.message + '\n');
this.emit('end');
})
)
// Load default json data
.pipe(data(function () {
return JSON.parse(fs.readFileSync(paths.data + path.basename('default.twig.json')));
}).on('error', function (err) {
process.stderr.write(err.message + '\n');
this.emit('end');
})
)
// Twig compiled
.pipe(twig()
.on('error', function (err) {
process.stderr.write(err.message + '\n');
this.emit('end');
})
)
.pipe(dest(paths.build));
}
function copyAssets() {
// Copy assets
return src(['./dist/assets/**/*.*','!./dist/assets/**/*.psd','!./dist/assets/**/*.*.map'],
del(paths.build + 'assets/**/*')
)
.pipe(gulpcopy(paths.build + 'assets', { prefix: 2 }));
}
// BrowserSync
function browserSync() {
browsersync({
server: {
baseDir: paths.build
},
notify: false,
browser: "google chrome",
// proxy: "0.0.0.0:5000"
});
}
// BrowserSync reload
function browserReload () {
return browsersync.reload;
}
// Watch files
function watchFiles() {
// Watch SCSS changes
watch(paths.scss + '**/*.scss', parallel(css))
.on('change', browserReload());
// Watch javascripts changes
watch(paths.js + '*.js', parallel(js))
.on('change', browserReload());
// Watch template changes
watch(['dist/templates/**/*.twig','dist/data/*.twig.json'], parallel(twigTpl))
.on('change', browserReload());
// Assets Watch and copy to build in some file changes
watch('dist/assets/**/*')
.on('change', series(copyAssets, css, css_vendors, js, browserReload()));
}
const watching = parallel(watchFiles, browserSync);
exports.js = js;
exports.css = css;
exports.default = parallel(copyAssets, css, js, twigTpl);
exports.watch = watching;
My gulp version:
"node": "18.12.1"
"gulp": "^4.0.2",
On terminal when i write gulp -v it shows:
CLI version: 2.3.0
Local version: 4.0.2
Expecting professional help
Since your gulpfile is a CommonJS module, use require instead of import:
const { src, dest, parallel, series, watch } = require('gulp');
const twig = require('gulp-twig');
const sass = require('gulp-sass');
const prefix = require('gulp-autoprefixer');
const data = require('gulp-data');
const sourcemaps = require('gulp-sourcemaps');
const concat = require('gulp-concat');
const plumber = require('gulp-plumber');
const browsersync = require('browser-sync');
const gulpcopy = require('gulp-copy');
const fs = require('fs');
const del = require('del');
const path = require('path');
Using an ESM style gulpfile is also an option, but it's not as simple as just replacing require with import (btw the syntax is import sass from 'gulp-sass';...), you will also need to rename the file to "gulpfile.mjs", change the style of your exports, and probably more.

Integrating GULP with node.js

I have a project in node.js for which I want to automate some backup and revision tasks in GULP.
I am able to successfully test following gulp code in terminal and everything working perfectly. The issue comes when I run gulp task from node.js code.
Gulp code:
var gulp = require('gulp');
var runSequence = require('run-sequence');
var rev = require('gulp-rev');
var format = require('date-format');
var dt = (new Date());
var gBkup = __dirname + '/backup/' + format.asString('ddMMyyyy_hhmm', dt);
var config = __dirname + '/gHelper.json', mnf = __dirname + '/rev-manifest.json';
var cssSrc = [], cssSrcO = [], cssSrcI = [];
var dirSrc = [], dirSrcO = [], dirSrcI = [];
gulp.task('init', function (){ // Initialize paths and all arrays containing file paths
var fexists = require('file-exists');
//console.log('Config exists: ' + fexists(config));
if (fexists(config)) {
config = require(config);
}
//console.log('Config object: ' + config);
if (fexists(mnf)) {
mnf = require(mnf);
}
for (var file in config.revision.ext_css) {
var fnm = __dirname + '/preview/' + config.revision.ext_css[file];
cssSrc.push(fnm);
if (mnf[config.revision.ext_css[file]] != "") {
var hnm = __dirname + '/live/' + mnf[config.revision.ext_css[file]];
cssSrcO.push(hnm);
console.log("Manifest: " + hnm);
}
}
for (var dir in config.revision.dir) {
dirSrc.push(__dirname + '/preview/' + config.revision.dir[dir]);
var dirnm = __dirname + '/live/' + config.revision.dir[dir];
dirnm = dirnm.substr(0, dirnm.length-3);
dirSrcO.push(dirnm);
console.log("Directory: " + dirnm);
}
// Files and directories will be ignored in revision
for (var file in config.revision.ext_css) {
cssSrcI.push('!' + __dirname + '/preview/' + config.revision.ext_css[file]);
}
for (var dir in config.revision.dir) {
dirSrcI.push('!' + __dirname + './preview/' + config.revision.dir[dir]);
}
//console.log('Ignore CSS: ' + cssSrcI);
//console.log('Ignore DIR: ' + dirSrcI);
});
// Revisioning Files
gulp.task('revisionCSS', function() { // Revise CSS scripts
var cssDest = __dirname + config.revision.ext_css_dest;
console.log('cssDestination: ' + cssDest);
return gulp.src(cssSrc)
.pipe(rev())
.pipe(gulp.dest(cssDest))
.pipe(rev.manifest({base: cssDest, merge: true}))
.pipe(gulp.dest(cssDest))
});
gulp.task('revInnerScripts', function () { // Revise javascripts
var dirDest = __dirname + config.revision.ext_dir_dest;
var cssDest = __dirname + config.revision.ext_css_dest;
console.log('dirInner: ' + dirDest);
console.log('cssInner: ' + cssDest);
return gulp.src(dirSrc)
.pipe(rev())
.pipe(gulp.dest(dirDest))
.pipe(rev.manifest({base: cssDest, merge: true}))
.pipe(gulp.dest(cssDest));
});
gulp.task('copyIgnoreRevision', function() { // Simply copy other/ignored files from array
var src = [__dirname + '/preview/**']
src = src.concat(cssSrcI);
src = src.concat(dirSrcI);
console.log(src)
return gulp.src(src)
.pipe(gulp.dest(__dirname + '/live'));
});
gulp.task('removeLive', function(callback) { // Removing files
var del = require('del');
var src = cssSrcO.concat(dirSrcO);
console.log("Removing Files: " + src);
return del(src);
});
gulp.task('backupLive', function() { // Backing up revision files before taking revision
// var src = ['./Live/**'];
gulp.src(cssSrcO).pipe(gulp.dest(gBkup));
return gulp.src(dirSrcO).pipe(gulp.dest(gBkup + "/js"));;
/* return gulp.src(cssSrcO, {read: false})
.pipe(clean());*/
});
gulp.task('backup', function(callback) { // Backup tasks list
runSequence('backupLive', 'removeLive', callback);
});
gulp.task('revise', ['copyIgnoreRevision', 'revisionCSS', 'revInnerScripts']);
gulp.task('revback', function (callback) {
runSequence('init', 'backup', 'revreplace', callback);
});
// Replacing references
gulp.task('revreplace', ['revise'], function(callback) { // In callback replace references for revised files
var revReplace = require('gulp-rev-replace');
var mReps = gulp.src(__dirname + '/rev-manifest.json');
return gulp.src(__dirname + '/preview/*.html')
.pipe(revReplace({manifest: mReps}))
.pipe(gulp.dest(__dirname + '/live'));
});
gHelper.json: Listing files which needs to be revised. Everything else will be copied to destination directory.
{
"revision": {
"ext_css" : [
"extie.css",
"responsive.css",
"style.css"
],
"ext_css_dest": "/live",
"dir": [
"js/*.js"
],
"ext_dir_dest": "/live/js"
}
}
Basic folder structure:
MainFolder/
gHelper.json
gulpfile.js
preview/
HTML files which contains references to revision files
Revision files (CSS and JS). CSS files are mentioned in gHelper.json
js/
Revision files (mainly js) which are to be revised as this folder is mentioned in gHelper.json and all files from the folder will be revised
When gulp task revback is invoked a folder live will be generated and added inside MainFolder. Again when revback is invoked, first, backup/{timestamp} folder will be generated taking backup of revised files only and then revision is made for live folder.
Lets see code from Node.js:
/* Publish client */
var gulp = require('gulp');
router.post('/api/:clientName/publish', function(req, res, next) {
var clientName = req.params.clientName;
var filePath = '/gulpfile'; // Full path for gulp file
console.log("Publish client: " + filePath);
try {
var gtask = require(filePath);
if (gulp.tasks.revback) {
console.log('gulp file contains task!');
gulp.start('revback');
}
} catch (err) {
return console.error(err);
}
});
Now the problem comes that sometimes gulp tasks are not being completed, rev-manifest.json is not created at proper position means inside MainFolder but created outside in the folder where this node.js lies.
Please let me know how to resolve the issue, Thanks.
Below is content of rev-manifest.json:
{
"dctConf.js": "dctConf-7c467cb7cb.js",
"extie.css": "extie-a8724bfb0c.css",
"responsive.css": "responsive-76492b9ad4.css",
"style.css": "style-770db73beb.css",
"translation.js": "translation-9687245bfb.js"
}
You could try changing the working directory in your gulpfile.js to the location of the gulpfile. Just add this at the top
process.chdir(__dirname);
Docs
https://nodejs.org/docs/latest/api/process.html#process_process_chdir_directory
https://nodejs.org/docs/latest/api/globals.html#globals_dirname
I have used gulp's native callbacks and removed run-sequence module.
E.g.:
gulp.task('revback', ['revise'], function(callback) {
var revReplace = require('gulp-rev-replace');
var mReps = gulp.src(__dirname + '/rev-manifest.json');
console.log('Manifest content: ' + mReps + ' && ' + __dirname + '/rev-manifest.json');
return gulp.src(__dirname + '/preview/*.html')
.pipe(revReplace({manifest: mReps}))
.pipe(gulp.dest(__dirname + '/live'))
.once('error', function(e) {
console.log('Error at revback: ' + e);
callback(e);
process.exit(1);
})
.once('end', function() {
console.log('Ending process at revback!');
callback();
process.exit();
});
});
gulp.task('revise', ['copyIgnoreRevision', 'revisionCSS', 'revInnerScripts']);
gulp.task('backupLive', ['init'], function() {
// var src = ['./Live/**'];
gulp.src(cssSrcO).pipe(gulp.dest(gBkup));
return gulp.src(dirSrcO).pipe(gulp.dest(gBkup + "/js"));
/* return gulp.src(cssSrcO, {read: false})
.pipe(clean());*/
});
This way, reverse chained to init function.

Parse main bower files (js, css, scss, images) to distribution via Gulp

We have recently switched from using a PHP asset manager to Gulp. We use bower to pull in our frontend packages and their dependencies.
Using simple Bower packages that only have JS files listed in 'main' is pretty straightforward and is easily done.
Using 'main-bower-files' we grab the required js files and concatenate them into one script file which we send to our site/script folder.
The fonts we can collect and move to a fonts/ folder in our site.
Then we hit a wall... What to do with images and their paths in the corresponding css/scss files.
To further complicate things we want images to keep some of their original folder layout so they don't get overridden.
We want to grab the css and scss (we use libsass) files and merge them with our own styles into one .css file.
But how can we make sure they still have working paths to the images that come with them.
The desired folder layout is as follows:
bower.json
gulpfile.js
package.json
bower_components/
site/
- css/styles.css
- fonts/
- images/
- bower-package-a/
- arrow.png
- gradient.png
- themea-a/
- arrow.png
- theme-b/
- arrow.png
- bower-package-b/
- arrow.png
- gradient.png
- script/
This is our Gulpfile so far:
// Include gulp
var gulp = require('gulp');
// Include Plugins
var bower = require('gulp-bower');
var browserSync = require('browser-sync').create();
var concat = require('gulp-concat');
var del = require('del');
var filter = require('gulp-filter');
var gutil = require('gulp-util');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var mainBowerFiles = require('main-bower-files');
var merge = require('merge-stream');
var newer = require('gulp-newer');
var plumber = require('gulp-plumber');
var pngquant = require('imagemin-pngquant');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var changed = require('gulp-changed');
var parallel = require("concurrent-transform");
var os = require("os");
var imageResize = require('gulp-image-resize');
var spritesmith = require('gulp.spritesmith');
var uglify = require('gulp-uglify');
// Paden
var bowerDest = 'site/script/lib/bower';
var imgSrc = 'src/images/**';
var imgDest = 'site/images';
var spriteImgDest = './src/images/sprite/';
var scriptSrc = 'src/script/**/*.js';
var scriptDest = 'site/script';
var stylesSrc = 'src/styles/styles.scss';
var stylesDest = 'site/css';
// Helpers
var onSassError = function(error) {
gutil.log('Sass Error', gutil.colors.red('123'));
gutil.beep();
console.log(error);
this.emit('end');
}
// Clean images Task
gulp.task('clean:images', function () {
return del([imgDest]);
});
// Clean script Task
gulp.task('clean:script', function () {
return del([scriptDest]);
});
// Clean image Task
gulp.task('clean:styles', function () {
return del([stylesDest]);
});
// Lint Task
gulp.task('lint', function() {
return gulp.src(scriptSrc)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
;
});
// Sass Task
gulp.task('sass', ['sprite'], function() {
return gulp.src(stylesSrc)
.pipe(plumber({
errorHandler: onSassError
}))
.pipe(sourcemaps.init())
.pipe(sass({
includePaths: [
'bower_components/compass-mixins/lib',
'bower_components/foundation/scss'
],
outputStyle: 'compressed'
}))
.pipe(sourcemaps.write('./map'))
.pipe(gulp.dest(stylesDest))
.pipe(browserSync.stream())
;
});
// Concatenate & Minify JS
gulp.task('script', function() {
return gulp.src(scriptSrc)
.pipe(concat('script.js'))
.pipe(gulp.dest(scriptDest))
.pipe(rename('script.min.js'))
.pipe(uglify())
.pipe(gulp.dest(scriptDest))
;
});
// Voeg de JS bestanden die gebruikt worden vanuit bower samen. Let op: modernizr volgt niet de standaard
// en wordt daarom niet meegenomen in mainBowerFiles(). Deze voegen we dus los toe.
gulp.task('bower:js', function() {
var modernizr = gulp.src('bower_components/modernizr/modernizr.js')
.pipe(rename('modernizr.min.js'))
.pipe(uglify())
.pipe(gulp.dest(scriptDest))
;
var frontend = gulp.src(mainBowerFiles())
.pipe(sourcemaps.init())
.pipe(filter('*.js'))
.pipe(concat('frontend.min.js'))
.pipe(uglify())
.pipe(sourcemaps.write('maps'))
.pipe(gulp.dest(scriptDest))
;
return merge(modernizr, frontend);
});
// Imagemin Task (compress images)
gulp.task('imagemin', function () {
return gulp.src([imgSrc, '!src/images/sprite{,/**}'])
.pipe(newer(imgDest))
.pipe(imagemin({
use: [pngquant()]
}))
.pipe(gulp.dest(imgDest))
.pipe(browserSync.stream())
;
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('browser-sync', function() {
// Serve files from the root of this project
browserSync.init({
proxy: "localhost/insyde/website_v6_devtools/site"
});
// add browserSync.reload to the tasks array to make
// all browsers reload after tasks are complete.
gulp.watch("./src/script/**/*.js", ['scripts-watch']);
});
// generate the x1 images from the big ones
gulp.task('generate-small-sprite-images', function () {
return gulp.src('./src/images/sprite/*-2x.png')
.pipe(newer(rename(function(path) {
path.basename = path.basename.slice(0, -3); //remove #2x label
})))
.pipe(parallel(
imageResize({
width: '50%',
height: '50%'
}), os.cpus().length
))
.pipe(rename(function(path) {
path.basename = path.basename.slice(0, -3); //remove #2x label
}))
.pipe(gulp.dest(spriteImgDest))
;});
gulp.task('sprite', ['generate-small-sprite-images'], function () {
var spriteData = gulp.src('./src/images/sprite/**/*.png').pipe(spritesmith({
imgName: 'sprite.png',
retinaImgName: 'sprite-2x.png',
cssName: 'sprite.scss',
imgPath: '../images/sprite.png',
retinaImgPath : '../images/sprite-2x.png',
retinaSrcFilter: '**/*-2x.png'
}));
// Pipe image stream through image optimizer and onto disk
var imgStream = spriteData.img
.pipe(imagemin())
.pipe(gulp.dest(imgDest));
// Pipe CSS stream through CSS optimizer and onto disk
var cssStream = spriteData.css
.pipe(gulp.dest('./src/styles/'));
// Return a merged stream to handle both `end` events
return merge(imgStream, cssStream);
});
// Watch Files For Changes
gulp.task('watch', function() {
gulp.watch('./src/script/**/*.js', ['lint', 'script']);
gulp.watch('./src/styles/**/*.scss', ['sass']);
gulp.watch('./src/images/**', ['imagemin']);
gulp.watch('./templates/**/*.html').on('change', browserSync.reload);
});
// Default Tasks
gulp.task('default', ['lint', 'sass', 'bower:js', 'script', 'imagemin', 'watch']);
gulp.task('frontend', ['lint', 'sprite', 'sass', 'bower:js', 'script', 'imagemin', 'browser-sync', 'watch']);
gulp.task('clean', ['clean:images', 'clean:script', 'clean:styles']);
// create a task that ensures the `scripts` task is complete before
// reloading browsers
gulp.task('scripts-watch', ['script'], browserSync.reload);
Got it working!
I used this as an example: https://github.com/jonkemp/gulp-useref/issues/60#issuecomment-77535822
What these tasks do is:
bower:assets
Copy all asset files (images and fonts) that are defined in the 'main' property of bower packages (which we find by using main-bower-files) to site/dist/ while keeping the original folder layout of the packages themself.
bower:styles
Parse each stylesheet that comes from main-bower-files (excluding two packages: foundation and compass-mixins) and rework the urls that point to the images and fonts that we copied earlier. This differs from the example in a way that the files in my situation aren't first copied to a .tmp directory, but get dealed with and then written to the site/css folder directly. I concatenate and minify the css, while using sourcemaps to make debugging easier.
//copy bower assets that need copying
gulp.task('bower:assets', function() {
return gulp.src(mainBowerFiles(), {
base: './bower_components'
})
.pipe(filter([
'**/*.{png,gif,svg,jpeg,jpg,woff,eot,ttf}',
'!foundation/**/*',
'!compass-mixins/**/*'
]))
.pipe(gulp.dest('./site/dist'));
});
//generate bower stylesheets with correct asset paths
gulp.task('bower:styles', function() {
return gulp.src(mainBowerFiles(), {
base: './bower_components'
})
.pipe(filter([
'**/*.{css,scss}',
'!foundation/**/*',
'!compass-mixins/**/*'
]))
.pipe(foreach(function(stream, file) {
var dirName = path.dirname(file.path);
return stream
.pipe(rework(reworkUrl(function(url) {
var fullUrl = path.join(dirName, url);
if (fs.existsSync(fullUrl)) {
bowerCopyFiles.push(fullUrl);
console.log(path.relative('css', fullUrl).replace(/bower_components/, 'dist'));
return path.relative('css', fullUrl).replace(/bower_components/, 'dist');
}
return url;
})));
}))
.pipe(sourcemaps.init())
.pipe(concat('bower.css'))
.pipe(minifyCss())
.pipe(sourcemaps.write('./map'))
.pipe(gulp.dest(stylesDest));
});
This all results in the following directory sturcture:
bower_components
site
css
bower.css
dist
bower-component-a
images
arrow.png
gradient.png
bower-component-b
images
arrow.png
gradient.png
Another option is to use the gulp-bower-normalize package, which will take the piped output from main-bower-files and then split them up based on the package and file extension, e.g.
gulp.src(mainBowerFiles(), { base: 'bower_components' })
.pipe(bowerNormalize({ bowerJson: './bower.json' }))
.pipe(gulp.dest('assets/vendor'));
You may have to tweak the main files in bower.js as well, but it works quite nicely. If you were using Bootstrap...
bower.json:
{
...
"dependencies": {
"bootstrap": "^3.3.6",
...
},
"overrides": {
"bootstrap": {
"main": [
"dist/css/bootstrap.min.css",
"dist/js/bootstrap.min.js",
"fonts/glyphicons-halflings-regular.eot",
"fonts/glyphicons-halflings-regular.svg",
"fonts/glyphicons-halflings-regular.ttf",
"fonts/glyphicons-halflings-regular.woff",
"fonts/glyphicons-halflings-regular.woff2"
],
"normalize": {
"fonts": ["*.eot", "*.svg", "*.ttf", "*.woff", "*.woff2"]
}
}
}
}
... it would generate the below structure:
assets/
|-- vendor/
|-- bootstrap/
|-- css/
| |-- bootstrap.min.css
|
|-- fonts/
| |-- glyphicons-halflings-regular.eot
| |-- glyphicons-halflings-regular.svg
| |-- glyphicons-halflings-regular.ttf
| |-- glyphicons-halflings-regular.woff
| |-- glyphicons-halflings-regular.woff2
|
|-- js/
|-- bootstrap.min.js
Another nice option it has is to flatten the structure, which may be more useful when bundling up vendor files.

NodeJs running ImageMagick convert all images from directory

This is basic imagemagick setup for node.js that i came across lately. I understand that question i'm asking is very newbie but i'm new to node js and imagemagick and i wanted to try to make it dynamic. Current script bellow is cropping one specific file, is there a way to make it to apply conversion to all the files from directory /before and then output it to directory /after ? Also the operation i want to do for all the images in directory is to apply watermark on each (crop operation in code is just from example).
var http = require("http");
var im = require("imagemagick");
var args = [
"image.png",
"-crop",
"120x80+30+15",
"output.png"
];
var server = http.createServer(function(req, res) {
im.convert(args, function(err) {
if(err) { throw err; }
res.end("Image crop complete");
});
}).listen(8080);
Yes, you can do it by implementing foreach by all files itself.
Also you will need to install async module:
npm install async
Example code:
var async = require('async'),
fs = require('fs'),
im = require('imagemagick'),
maxworkers = require('os').cpus().length,
path = require('path');
module.exports = resize;
function resize(params) {
var queue = async.queue(resizeimg, maxworkers);
fs.readdir(params.src, function(err, files) {
files.forEach(function(file) {
queue.push({
src: path.join(params.src, '/', file),
dest: path.join(params.dest, '/', file),
width: params.width,
height: params.height
})
});
});
}
function resizeimg(params, cb) {
var imoptions = {
srcPath: params.src,
dstPath: params.dest
};
if (params.width !== undefined) imoptions.width = params.width;
if (params.height !== undefined) imoptions.height = params.height
im.resize(imoptions, cb);
}
Then in you code:
var http = require("http");
var resize = require("./resize");
var server = http.createServer(function(req, res) {
resize({
src: '/source/folder',
dest: '/destination/folder',
width: 300
});
}).listen(8080);

fabric.js on node.js loadFromDatalessJSON moves objects when in a group

I am serializing a canvas on the client, and post it to a node.js server (ubuntu 14.10, with node.js version v0.10.34 and fabric 1.4.13).
On the client canvas, objects are in a group.
The problem is, the objects are moved when de-serialized on the server.
Client code:
$(function(){
fc= new fabric.Canvas('myCanvas');
fc.setBackgroundColor('white');
group = new fabric.Group([], { hasControls:false, hasBorders:true, top:-fc.getHeight(), left:-fc.getWidth(), width:2*fc.getWidth(), height:2*fc.getHeight(), hoverCursor:'default' });
fc.add(group);
// create a rectangle object
var rect = new fabric.Rect({
left: 150,
top: 100,
fill: 'red',
width: 20,
height: 20
});
// "add" rectangle onto canvas
group.add(rect);
var rect2 = new fabric.Rect({
left: 100,
top: 150,
fill: 'blue',
width: 20,
height: 20
});
group.add(rect2);
fc.renderAll();
$.post( window.location.origin+':8124/', {
width: group.getWidth(),
height: group.getHeight(),
data: encodeURI(JSON.stringify(fc.toDatalessJSON()))
}, function( data ) {}
);
});
Server code:
var fabric = require('fabric').fabric;
var express = require('express');
var app = express();
var fs = require('fs');
var PORT = 8124;
var bodyParser = require('body-parser')
app.use(bodyParser.json({ limit: '50mb'}) ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true,
limit: '50mb'
}));
app.post('/', function(req, res){
console.log('Post received');
if (req.body) {
res.writeHead(200, { 'Content-Type': 'image/png' });
var w=parseInt(req.body.width);
var h=parseInt(req.body.height);
var canvas = fabric.createCanvasForNode(w, h);
console.log(req.body.data);
out = fs.createWriteStream(__dirname + '/mindmap.png');
canvas.loadFromDatalessJSON(decodeURI(req.body.data), function() {
canvas.renderAll();
console.log(JSON.stringify(canvas.toDatalessJSON()));
var stream = canvas.createPNGStream();
stream.on('data', function(chunk) {
out.write(chunk);
console.log('writing chunk');
});
stream.on('end', function() {
out.end();
});
});
}
});
app.listen(PORT);
The console.log statement shows that the two rects are created (left:15, top-35) and (left:-35, top:15) respectively.
On the client, top/left object properties are relative to center of the group.
This is why I create the group with -fc.getWidth and-fc.getHeight left and top respectively. This works fine on the client.
Maybe this is not the case on the server?
EDIT: this seems to be an issue with loadFromDatalessJSON, at least on node.
Running the following code on the node server shows that top/left properties of the rectangles are wrong after serializing the first canvas and deserializing into the second one:
var fabric = require('fabric').fabric;
var fs = require('fs');
var canvas = fabric.createCanvasForNode(200, 200);
canvas.setBackgroundColor('white');
var out = fs.createWriteStream(__dirname + '/mindmap.png');
var group = new fabric.Group([], { top:-200, left:-200, width:400, height:400});
canvas.add(group);
var rect = new fabric.Rect({
left:150,
top:100,
fill:'red',
width:20,
height:20
});
group.add(rect);
var rect2 = new fabric.Rect({
left:100,
top:150,
fill:'blue',
width:20,
height:20
});
group.add(rect2);
canvas.renderAll();
console.log(JSON.stringify(canvas.toDatalessJSON()));
var canvas2 = fabric.createCanvasForNode(200, 200);
canvas2.loadFromDatalessJSON(canvas.toDatalessJSON());
canvas2.renderAll();
var stream = canvas2.createPNGStream();
stream.on('data', function(chunk) {
out.write(chunk);
console.log('writing chunk');
});
stream.on('end', function() {
out.end();
console.log('png image generated');
});
console.log(JSON.stringify(canvas2.toDatalessJSON()));
Next step is to run similar code on the client and see if the problem exists as well.
EDIT2: the same problem occurs on the client, and with toJSON as well instead of toDatalessJSON. Can someone help? Is this a known issue with groups serialization/deserialization? Is there a workaround?
Thanks
After searching for similar issues, it looks like this is very similar to [#1159] [https://github.com/kangax/fabric.js/issues/1159]
But this issue is supposed to be fixed, and I don't have any transform on my canvas ...
I had this problem and fixed it by installing the latest version from the github releases section: https://github.com/kangax/fabric.js/releases

Resources