How to debug a Gulp task? - javascript

How do I debug a gulp task defined in my gulpfile.js with a debugger such as the Google Chrome debugger, stepping through the task's code line by line?

With Node.js version 6.3+ you can use the --inspect flag when running your task.
To debug a gulp task named css:
Find out where your gulp executable lives. If gulp is installed locally, this will be at node_modules/.bin/gulp. If gulp is installed globally, run which gulp (Linux/Mac) or where gulp (Windows) in a terminal to find it.
Run one of these commands according to your version of Node.js. If required, replace ./node_modules/.bin/gulp with the path to your gulp installation from step 1.
Node.js 6.3+: node --inspect --debug-brk ./node_modules/.bin/gulp css
Node.js 7+: node --inspect-brk ./node_modules/.bin/gulp css
Use Chrome to browse to chrome://inspect.
The --debug-brk (Node.js 6.3+) and --inspect-brk (Node.js 7+) flags are used to pause code execution on the first line of code of your task. This gives you a chance to open up the Chrome debugger and set breakpoints before the task finishes.
If you don't want the debugger to pause on first line of code, just use the --inspect flag.
You can also install the Node.js Inspector Manager (NIM) extension for Chrome to help with step 3. This will automatically open up a Chrome tab with the debugger ready to go, as an alternative to manually browsing to a URL.

For anyone using VS Code 1.10+
Open the debug panel.
Click on the settings icon.
Click on Add Configuration button.
Choose Node.js: Gulp Task.
This is how your launch.json file should look.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Gulp task",
"program": "${workspaceFolder}/node_modules/gulp/bin/gulp.js",
"args": [
"yourGulpTaskName"
]
}
]
}

If you are using webstorm you can right click the task in the gulp panel and select debug.

Thanks user2943490, on Windows I found this version worked for me:
node --inspect --debug-brk ./node_modules/gulp/bin/gulp.js --verbose

If you are using gulp-nodemon you can do this in your gulpfile.
Just pass it the execMap option:
gulp.task('default', function() {
nodemon({
script: 'server.js',
ext: 'js',
execMap: {
js: "node --inspect"
}
})
}
Hope this helps.

Version (node v8.11.3, npm 6.2.0, gulp 3.9.1)
Windows 10 & git bash
Install Node.js V8 --inspector Manager (NiM) & set to your preference
Try this:
node --inspect-brk ./node_modules/gulp/bin/gulp.js --verbose

I liked the answer of #Avi Y. but I suppose people would had appreciated a more complete script :
gulp.task('nodemon', ['sass'], function(cb) {
var started = false;
consoleLog('nodemon started');
return nodemon({
//HERE REMOVE THE COMMENT AT THE BEGINING OF THE LINE YOU NEED
//exec: 'node --inspect --debug-brk node_modules/gulp/bin/gulp.js',
exec: 'node --inspect --debug-brk',
//exec: 'node --inspect',
script: path.server,
ignore: ['*/gulpfile.js', 'node_modules/*'],
verbose: true
}).on('start', function() {
if (!started) {
cb();
started = true;
}
}).on('restart', function() {
consoleLog('nodemon restarted the server');
});});

Related

Mocha lmieulet:meteor-coverage code coverage error - failed to save

I’m trying to generate and save an LCOV code coverage report file from a mocha test suite for my server in my (non-Typescript) Meteor app. To enable this, I’ve added the lmieulet:meteor-coverage meteor package, the meteortesting:mocha meteor package, and the instanbul babel plugin.
I've also written a ./.coverage.json file:
{
"include": [
"**/*.js",
"**/packages/lmieulet_meteor-coverage.js"
],
"remap": {
"format": ["html", "clover", "cobertura", "json", "json-summary", "lcovonly", "teamcity", "text", "text-summary"]
},
"output": "./.coverage"
}
And added config for the babel plugin in package.json:
"babel": {
"env": {
"COVERAGE": {
"plugins": [
"istanbul"
]
}
}
}
And I’ve written an npm script (named “test-cov”) which includes the necessary env variables to run the test with coverage.
cross-env BABEL_ENV=COVERAGE TEST_CLIENT=0 COVERAGE_OUT_LCOVONLY=1 COVERAGE=1 COVERAGE_VERBOSE=1 COVERAGE_APP_FOLDER=$(pwd)/ meteor test --port 3030 --once --driver-package meteortesting:mocha
With all this set up, I'm expecting the code coverage report to successfully generate when I run "npm run test-cov".
However, when I do run it, I keep getting the following error:
Error: Failed to save lcov coverage... at packages/meteortestingLmocha/server.handlecoverage.js:37:18
I’ve tried:
Switching between the absolute path for ‘output’ in coverage.json file and relative path (./.coverage)
Updating the versions of meteortesting:mocha as well as the overall Meteor version of my app
Opening chmod permissions to 777 for ./.coverage folder (to be written into)
One complication may be that we also have a second testing suite (Jest), but I don’t believe that’s being invoked anywhere as a result of running “test-cov”
Does anyone have an idea of why this isn’t working? I’m at a loss about what to do, partly because the error message here is so brief…

How to avoid permission issues when using denon

I was running denon, which is like nodemon in node, but I'm getting permission issues even when I've manually specified the relevant flags (specifically --allow-net flag.)
How do I run my app with denon so I don't have to keep restarting?
Without knowing the exact error it's hard to give you the correct answer, but denon is unstable, it has several issues.
One of those errors that you might be affecting you is if you're trying to watch a folder that you may not have ownership you'll get:
error: Uncaught PermissionDenied: Permission denied (os error 13)
for example, if I run denon on /tmp I get that error thrown, even if the folder has all permissions.
Even though nodemon works perfectly on /tmp.
My recommendation is to use nodemon until denon is stable or until there's a better tool for deno.
You can do so by using --exec flag
nodemon --exec deno run --allow-net index.ts
For convenience you can use nodemon.json with the following content:
{
"execMap": {
"js": "deno run --allow-net",
"ts": "deno run --allow-net"
},
"ext": "js,json,ts"
}
And now just use: nodemon index.ts
You can create a denon.json file in your project root.
{
"scripts": {
"start": "deno run --allow-env --allow-net server.ts"
}
}
Then you can run the script this way (assuming denon installed):
denon start
https://deno.land/x/denon
Hope it helps!
adding --allow-net solved it for me.
for some reason creating the denon.json file manually didn't work, so I had to run
deno --init and add --allow-net to the start cmd
"start": {
"cmd": "deno run --allow-net app.ts",
"desc": "run my app.ts file"
}

Set environment mode and output messages when starting a gulp task

I'm wondering how I can output messages to the terminal when I run a gulp process and how I can set an environment to run tasks in specific ways.
I'm sure I've seen something like gulp scripts:dev before but don't know how to use, can anyone advice how I can do this?
How would you run the default task this way, gulp deafult:dev?
Is it possible to ask the user which environment they want to run the task for in the terminal when the execute the gulp command, if they don't specify it.
I've used the gulp-if plugin to achieve this but it works slightly differently, you need to set a node environment variable before running gulp i.e. NODE_ENV=dev gulp.
var gulp = require('gulp'),
sass = require('gulp-ruby-sass'),
gulpif = require('gulp-if'),
shell = require('gulp-shell');
var isDev = process.env.NODE_ENV === 'dev';
// gulp-shell task to output messages to terminal
gulp.task('info', shell.task([
'echo run in developer mode with this command: NODE_ENV=dev gulp'
]));
// Styles Task
// Uses gulp-if plugin to run task differently dependent on env.
gulp.task('styles', ['info'], function () { // eslint-disable-line strict
return sass('css/sass/*.scss', {
style: gulpif(!isDev,'compressed','expanded'),
cacheLocation: 'css/sass/.sass-cache',
sourcemap: isDev
})
[...code ommitted...]
});
gulp.task('default', ['h','styles']);
Also I've used gulp-shell above to output messages to the terminal, but it's pretty basic. Is there anyway I can do something similar with line breaks and colours with the message I output to the terminal.
Take a look at gulp-environments - you can set as many as you like but dev and prod are sufficient for most. You can define each in the gulpfile and set different events to occur from within each gulp script. So your styles script can contain a .pipe(dev(some dev only sourcemap code))and a .pipe(prod(some mini fixed build code)). You can run the script from git bash with an --env flag... gulp --env dev or gulp --env prod. And run two completely different build cycles from more or less the same script. You set your default gulp task to run all your page scripts and it will only execute the ones for each environment as it loops.
To output messages to the terminal you can require gulp-util node module.
Example code:
gulp.task('test', () => {
gutil.log(gutil.colors.yellow('=== Testing ==='));
});

Gulp error in WebStorm: Failed to list gulp tasks

My WebStorm has stopped read and run gulp tasks.
It was working fine until last Friday.
This is an error that appears in console:
Failed to list gulp tasks in questionary/gulpfile.js: Failed to parse
JSON -> Unterminated array at line 1 column 5 path $[1] * Edit
settings
$ /usr/local/bin/node
/Users/rkon2006/Projects/My/questionary/node_modules/gulp/bin/gulp.js
--no-color --gulpfile /Users/rkon2006/Projects/My/questionary/gulpfile.js --tasks-json
[17:26:14] Using gulpfile ~/Projects/My/questionary/gulpfile.js
[17:26:14] Starting 'default'... Default task...
This is the code from my gulpfile.js (it doesn't start even with this code):
var gulp = require('gulp');
gulp.task('default', function () {
console.log('Default task...');
});
Process finished with exit code 0
I use gulp v4.0, node js 4.1.1 (tried defferent versions from 0.10.28 up to 4.1.1) and npm 2.14.4.
Do you have any ideas about this?
I have the same problem with webstorm after install a updated version of node.
The solution for me is the following:
In the block Gulp where webstorm show the list of task, click the cog icon and select gulp settings, in the section "Gulp package" add the path to the local gulp package(the gulp inside the node_modules in your project).
Example of path: yourproject\node_modules\gulp
Update node version and npm itself, that did the trick.
The problem is that some text is logged to standard output stream when evaluating gulpfile.js, but before running any gulp task (i.e. logging happens outside of gulp tasks);
possible workarounds:
Avoid logging anything to standard output stream outside of gulp
tasks.
Or
Don't log to standard output stream if it's started for listing
tasks, like:
if (!isListingTasks()) {
console.log('[my info]');
}
function isListingTasks() {
return process.argv[process.argv.length - 1] === '--tasks-json';
}
I was having same problem and it was fixed by selecting different Node Interpreter version e.g. in the below image I selected 8.9.2 and then clicked small refresh button in Gulp window and the issue was fixed.

Using node-inspector with Grunt tasks

Does someone used node-inspector with Grunt for application debugging? If not, Can you recommend a debugging tool for Grunt based apps?
I'm working with nodejs for a server side app and I have Grunt to use separated tasks (this is because users can execute tasks separately).
To run grunt in debug, you need to pass the grunt script to node explicitly:
node-debug $(which grunt) task
and put a debugger; line in your task. node-inspector will then open a browser with debugging tools.
Edit 28 Feb 2014
node-inspector has added the command node-debug, which launches node in a --debug state and opens the browser to the node-inspector page, stopping when it hits the first debugger line or set breakpoint.
Edit 30 January 2015
On Windows, things are a touch more complicated. See the answer from #e.gluhotorenko for instructions.
Windows solution
Run
node --debug-brk c:\Users\username\AppData\Roaming\npm\node_modules\grunt-cli\bin\grunt taskname
from cmd in the directory with your Gruntfile.js. Do not forget to put debugger; line in necessary places.
To debug, we have to modify the grunt file under bin. On my machine, grunt is installed globally, so I went to /usr/local/lib/node_modules/grunt/bin
I opened the file and modified:
#!/usr/bin/env node
To
#!/usr/bin/env node --debug-brk
--debug-brk will break on the first line of javascript ran.
Doing that alone isn't quite enough though, since you won't be able to find you're grunt task js file in the drop down in node inspector, so you have to modify the file you're interested in debugging by adding debugger; where you want the breakpoint to happen.
Now you can click continue after the first break, and you'll break on you're debugger; line
Pretty kludgy, but it's the only way I've found so far.
I recently created grunt-node-inspector to easily configure node-inspector with the rest of your grunt workflow, check it out: https://github.com/ChrisWren/grunt-node-inspector
Here is a section of a Gruntfile which illustrates how you can debug a grunt task using grunt-node-inspector, grunt-concurrent, and grunt-shell: https://github.com/CabinJS/Cabin/blob/master/Gruntfile.js#L44-L77
I have done a task to run my app and launch node-inspector.
It is far better than current proposition, you just have to add this task in gruntfile:
grunt.registerTask('debug', 'My debug task.', function() {
var done = this.async();
grunt.util.spawn({
cmd: 'node',
args: ['--debug', 'app.js'],
opts: {
//cwd: current workin directory
}
},
function (error, result, code) {
if (error) {
grunt.log.write (result);
grunt.fail.fatal(error);
}
done();
});
grunt.log.writeln ('node started');
grunt.util.spawn({
cmd: 'node-inspector',
args: ['&'],
opts: {
//cwd: current workin directory
}
},
function (error, result, code) {
if (error) {
grunt.log.write (result);
grunt.fail.fatal(error);
}
done();
});
grunt.log.writeln ('inspector started');
});
Great answers here. In 2017, now you can do
node --inspect --debug-brk $(which grunt) taskName
Which prints something like.
To start debugging, open the following URL in Chrome:
chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/232652c3-f63c-4b00-8de9-17dfad5db471
Open that URL in chrome, and you're good to go!
I'm using Node 7.3.0 and I'm on Mac. You might have to follow some of the advice in other posts to get it going on Windows.
2019 update
If you want to launch the grunt task in debug mode and break at first line:
node --inspect-brk $(which grunt) taskName
If you want to launch the grunt task in debug mode at a specific port:
node --inspect-brk=8080 $(which grunt) taskName
if you want to attache VSCODE to the node process running the debugging session of grunt, use the following configuration in vscode:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach by port IP 5656",
"port": 8080
}
]
}

Categories

Resources