npm del error in gulpfile Visual Studio 2015 - node.js

I'm using the del package in my gulpfile as part of a clean task.
Below are the the versions of things I'm using
Visual Studio 2015 Community
Node.js v2.11.3
gulp v3.9.0
del v2.0.2
This is an extract from my gulp file:
var gulp = require('gulp');
var del = require('del');
var config = require('./gulp.config')();
var $ = require('gulp-load-plugins')({ lazy: true });
gulp.task('images', ['clean-images'], function () {
log('Copying and compressing the images');
return gulp
.src(config.images)
.pipe($.imagemin({optimizationLevel: 4}))
.pipe(gulp.dest(config.build + 'images'));
});
gulp.task('clean-images', function (done) {
clean(config.build + 'images/**/*.*', done);
});
function clean(path, done) {
log('Cleaning: ' + $.util.colors.blue(path));
del(path, done);
}
When I run the task images from the command prompt using gulp images the clean-images task executes but never finishes. It errors with the lines:
[16:10:45] Using gulpfile ~\Documents\Visual Studio 2015\Projects\**\Gulpfile.js
[16:10:46] Starting 'clean-images'...
[16:10:46] Cleaning: build/images/**/*.*
Process terminated with code 0.
As a result the rest of the images task doesn't execute.
The images task runs fine when I remove the clean-images dependency.
Don't suppose anyone has seen this issue before, and knows how to correct it?
Thanks

I think you've encountered the same error as this user : the del module doesn't use callbacks anymore, but promises. done is never called, so the clean and images task run concurrently, which causes an error.
You could just return from the clean method :
gulp.task('clean-images', function () {
return clean(config.build + 'images/**/*.*');
});
function clean(path) {
log('Cleaning: ' + $.util.colors.blue(path));
return del(path);
}

Related

Can I split my gulp tasks between different files when using Visual Studio?

I'm using Visual Studio 2015 and I have gulpfile that I run with the gulp task manager.
The file is getting bigger and bigger. Is there some way that I can split the tasks into more than one file. If there is then I would really appreciate a very small example of how I can do this.
Yes, as the gulp documentation explains: https://github.com/gulpjs/gulp/blob/master/docs/recipes/split-tasks-across-multiple-files.md
This is depreciated and will not be supported in gulp 4.0.
gulpfile.js
var requireDir = require('require-dir');
var tasks = requireDir('./tasks');
Or with gulp-require-tasks
gulpfile.js
// Require the module.
var gulpRequireTasks = require('gulp-require-tasks');
// Call it when neccesary.
gulpRequireTasks({
path: __dirname + '/tasks' // This is default
});
tasks/one.js
module.exports = {
dep: ['clean:styles'],
fn: function (gulp, callback) {
return gulp.src('...')
.pipe(plugin())
.dest('...');
}
};

Inconsistent Results with Running Gulp from Visual Studio on Post Build

I'm running gulp 3.9.0 and calling some gulp commands from Visual Studio 2013. The flow is such that whenever I build in VS, gulp should clean my temporary and output files, then after a successful build, compile my javascript assets into one file.
The problem is that, I've noticed that after running "gulp build", sometimes my assets are not generated at all. This even happens on the command line. After running "gulp clean" (which removes the output), I have to run "gulp build" twice just to see the output materialize. It's as if gulp is failing silently. Not sure if this is an issue with Node running on Windows or if I have misconfigured something.
Note that VS is responsible for compiling all TypeScript files into a single .js in the \output folder.
Apologies in advanced if there is a better way to do what I'm trying to do. Still a gulp/node newbie.
VS Pre-Build:
gulp clean
VS Post-Build:
gulp build
gulpfile.js:
var gulp = require('gulp');
var del = require('del');
var concat = require('gulp-concat');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var templateCache = require('gulp-angular-templatecache');
var concatCss = require('gulp-concat-css');
var minifyCss = require('gulp-minify-css');
gulp.task("cleanOutdatedLibraries", function(){
del("./Libs/*");
del(['./myapp.js', './myapp.min.js', './myapp.css'])
});
gulp.task("cleanTemporaryFiles", function(){
del("./output/*");
});
/** Run gulp clean on prebuild */
gulp.task('clean', ["cleanOutdatedLibraries", "cleanTemporaryFiles"])
gulp.task('copyNewestLibraries', function(){
var bowerFiles = ['angular/angular.min.js',
'angular/angular.js',
'angular/angular.min.js.map',
'angular-ui-router/release/angular-ui-router.min.js',
'angular-local-storage/dist/angular-local-storage.min.js',
'jquery/dist/jquery.min.js',
'jquery/dist/jquery.min.map',
'lodash/lodash.min.js',
'angular-resource/angular-resource.min.js',
'angular-resource/angular-resource.min.js.map',
'momentjs/min/moment.min.js',
'angular-loading-bar/src/loading-bar.js',
'ngDialog/js/ngDialog.min.js'];
gulp.src(bowerFiles, {cwd: "./bower_components/"})
.pipe(gulp.dest('./Libs'));
});
gulp.task('copyThirdPartyLibraries', function(){
var thirdPartyFiles = ['jquery-ui.min.js',
'angular-sanitize.min.js'];
gulp.src(thirdPartyFiles, {cwd: "./_thirdparty/"})
.pipe(gulp.dest('./Libs'));
});
/** Merge all Angular JS HTML templates into a cache */
gulp.task('mergeHtmlTemplatesIntoAngularCache', function(){
gulp.src('app/**/*.html')
.pipe(templateCache("templates.js", {
module: "myapp"
}))
.pipe(gulp.dest('./output/'));
});
gulp.task('produceMinfiedApp', function(){
gulp.src(['app/**/*.js', 'output/typescripts.js'])
.pipe(concat('bundle.min.js'))
.pipe(ngAnnotate())
.pipe(uglify())
.pipe(gulp.dest('./output/'));
gulp.src(['output/bundle.min.js', 'output/templates.js'])
.pipe(concat('myapp.min.js'))
.pipe(gulp.dest('./'));
});
gulp.task('produceApp', function(){
gulp.src(['app/**/*.js', 'output/typescripts.js'])
.pipe(concat('bundle.js'))
.pipe(ngAnnotate())
.pipe(gulp.dest('./output/'));
gulp.src(['output/bundle.js', 'output/templates.js'])
.pipe(concat('myapp.js'))
.pipe(gulp.dest('./'));
});
gulp.task('mergeStyles', function(){
gulp.src(['Styles/**/*.css'])
.pipe(concat('styles.css'))
.pipe(gulp.dest("./output/"));
gulp.src(['app/**/*.css'])
.pipe(concat('app.css'))
.pipe(gulp.dest("./output/"));
gulp.src(['output/styles.css', 'output/app.css'])
.pipe(concatCss("./myapp.css"))
.pipe(minifyCss({compatibility: 'ie10'}))
.pipe(gulp.dest('./'));
});
/** Run gulp build on post build */
gulp.task('build', ["copyNewestLibraries",
"copyThirdPartyLibraries",
"mergeHtmlTemplatesIntoAngularCache",
"produceMinfiedApp",
"produceApp",
"mergeStyles"]);
/** Run gulp build on post build */
gulp.task('build', ["copyNewestLibraries",
"copyThirdPartyLibraries",
"mergeHtmlTemplatesIntoAngularCache",
"produceMinfiedApp",
"produceApp",
"mergeStyles"]);
These tasks (copyNewestLibraries, produceApp, etc.) run asynchronously, in no particular order. E.g. produceApp may finish before copyNewestLibraries, which is probably not what you want.
See How to run Gulp tasks sequentially one after the other for more info.

How to package node webkit app

I'm developing my first node webkit app. I'm confused about packing the files. Is the end product a single file that can be executed ?
The end result will not be a single executable, you must also include some DLLs in your zip-file.
These line in github made me more confused.
How is the packaging done ?
Do I need to include the webkit files also in the package or just the files I have created ?
I packaged my node-webkit app successfully for various platforms by using the below gulp script. Below is the script which is self explanatory.
Reference : https://github.com/nwjs/nwbuilder/blob/master/example/Gulpfile.js
var NwBuilder = require('nw-builder');
var gulp = require('gulp');
var gutil = require('gulp-util');
gulp.task('nw', function () {
var nw = new NwBuilder({
version: '0.12.3',
files: '../nodepoc/**',
platforms: ['osx64','win32','win64']
});
// Log stuff you want
nw.on('log', function (msg) {
gutil.log('nw-builder', msg);
});
// Build returns a promise, return it so the task isn't called in parallel
return nw.build().catch(function (err) {
gutil.log('nw-builder', err);
});
});
gulp.task('default', ['nw']);
Save the file as gulpFile.js. In terminal , simply run gulp command in the same location as that of the gulpFile.js and it will download the necessary node-webkit distributions for the platforms and build the package for you.

Start gulp task from another node.js script

I'm using script like this:
run.js:
var gulp = global.gulp = require('gulp');
require('./gulpfile.js');
//interaction
gulp.start('zip');
gulpfile.js:
global.gulp = global.gulp || require('gulp');
gulp.task('zip', function () {});
And start: node run.js
I need it because I need collect some data via inquirer.prompt() before task start.
Everything works, but console freeze cursor after script end(in PHPStorm).
I don't understand why. If I run task via gulp, it's ok.
As mentioned by Aperçu in the comments, try letting gulp know that you're done your task.
Change
gulp.task('zip', function () {});
to
gulp.task('zip', function (done) {done()});

Is there a way to know that nodeunit has finished all tests?

I need to run some code after nodeunit successfully passed all tests.
I'm testing some Firebase wrappers and Firebase reference blocks exiting nodeunit after all test are run.
I am looking for some hook or callback to run after all unit tests are passed. So I can terminate Firebase process in order nodeunit to be able to exit.
Didn't found a right way to do it.
There is my temporary solution:
//Put a *LAST* test to clear all if needed:
exports.last_test = function(test){
//do_clear_all_things_if_needed();
setTimeout(process.exit, 500); // exit in 500 milli-seconds
test.done();
}
In my case, this is used to make sure DB connection or some network connect get killed any way. The reason it works is because nodeunit run tests in series.
It's not the best, even not the good way, just to let the test exit.
For nodeunit 0.9.0
For a recent project, we counted the tests by iterating exports, then called tearDown to count the completions. After the last test exits, we called process.exit().
See the spec for full details. Note that this went at the end of the file (after all the tests were added onto exports)
(function(exports) {
// firebase is holding open a socket connection
// this just ends the process to terminate it
var total = 0, expectCount = countTests(exports);
exports.tearDown = function(done) {
if( ++total === expectCount ) {
setTimeout(function() {
process.exit();
}, 500);
}
done();
};
function countTests(exports) {
var count = 0;
for(var key in exports) {
if( key.match(/^test/) ) {
count++;
}
}
return count;
}
})(exports);
As per nodeunit docs I can't seem to find a way to provide a callback after all tests have ran.
I suggest that you use Grunt so you can create a test workflow with tasks, for example:
Install the command line tool: npm install -g grunt-cli
Install grunt to your project npm install grunt --save-dev
Install the nodeunit grunt plugin: npm install grunt-contrib-nodeunit --save-dev
Create a Gruntfile.js like the following:
module.exports = function(grunt) {
grunt.initConfig({
nodeunit : {
all : ['tests/*.js'] //point to where your tests are
}
});
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.registerTask('test', [
'nodeunit'
]);
};
Create your custom task that will be run after the tests by changing your grunt file to the following:
module.exports = function(grunt) {
grunt.initConfig({
nodeunit : {
all : ['tests/*.js'] //point to where your tests are
}
});
grunt.loadNpmTasks('grunt-contrib-nodeunit');
//this is just an example you can do whatever you want
grunt.registerTask('generate-build-json', 'Generates a build.json file containing date and time info of the build', function() {
fs.writeFileSync('build.json', JSON.stringify({
platform: os.platform(),
arch: os.arch(),
timestamp: new Date().toISOString()
}, null, 4));
grunt.log.writeln('File build.json created.');
});
grunt.registerTask('test', [
'nodeunit',
'generate-build-json'
]);
};
Run your test tasks with grunt test
I came across another solution how to deal with this solution. I have to say the all answers here are correct. However when inspecting grunt I found out that Grunt is running nodeunit tests via reporter and the reporter offers a callback option when all tests are finished. It could be done something like this:
in folder
test_scripts/
some_test.js
test.js can contain something like this:
//loads default reporter, but any other can be used
var reporter = require('nodeunit').reporters.default;
// safer exit, but process.exit(0) will do the same in most cases
var exit = require('exit');
reporter.run(['test/basic.js'], null, function(){
console.log(' now the tests are finished');
exit(0);
});
the script can be added to let's say package.json in script object
"scripts": {
"nodeunit": "node scripts/some_test.js",
},
now it can be done as
npm run nodeunit
the tests in some_tests.js can be chained or it can be run one by one using npm

Resources