Using node-inspector with Grunt tasks - javascript

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
}
]
}

Related

Fast Refresh with Next.js development mode in VS Code Remote Container/devcontainer

I can't get Next.js' Fast Refresh feature to work with a VS Code Remote Container. I can run npm run dev and see the app running on localhost on my machine, so the container works fine - only the Fast Refresh has no effect at all.
Next.js version: v11.0.1
I tried this both with Windows 10 and Ubuntu 20.04 (on WSL 2).
I already tried to use a custom webpack middleware in the next.config.js like so (see https://github.com/vercel/next.js/issues/2179#issuecomment-316568536):
module.exports = {
webpackDevMiddleware: (config) => {
// Solve compiling problem via vagrant
config.watchOptions = {
poll: 1000, // Check for changes every second
aggregateTimeout: 300, // delay before rebuilding
};
return config;
},
};
...which will trigger a recompile on code changes, but the browser does not update.
Also, the requests to "HMR" are failing:
How to reproduce:
Install the Remote Containers extension
Open any new folder
Open the command palette and type/select "Remote-Containers: Rebuild and Reopen in Container"
Type/select "Node.js"
Type/select version "16" and wait for the container to start
Go to the .devcontainer folder and open the devcontainer.json
Edit the config by adding "forwardPorts": [3002], to make the app available on your host and rebuild the container (via VS Code's command palette)
From the terminal, install Next.js, e.g.: npx create-next-app --use-npm --example with-typescript-eslint-jest my-app
Move all the files from my-app to your VS Code project root folder. This has to be done because create-next-app does not work installing in the project root folder via ., because there's already the .devcontainer folder.
Optional: Create a next.config.js and add the snippet for the Webpack dev middleware as seen above
Edit the package.json script to use a specific port: "dev": "next dev -p 3002", (or, if you use WSL 2: next dev -p 3002 -H ::)
From the terminal, start the app npm run dev
Open the browser on http://localhost:3002
The app is showing. Make changes in the code -> even a recompiled app will not show the changes in the browser. A reload of the page in the browser will show the changes though.
With Create React App, there's an advanced configuration without ejecting (called CHOKIDAR_USEPOLLING), which makes their Fast Refresh work with Remote Containers.
Earlier I created a feature request, but maybe someone already managed to make this work without huge changes in the configuration/setup?
A lot has changed between me noticing this issue and the current version of Next.js (v12.1.6).
I just tried it out again and it finally seems to work! 🥳
I'm going to change my Next.js projects to use devcontainers and maybe other stuff does not work, but at least for Fast Refresh, this topic is solved.
If you're following the steps above, the most basic setup should look like the following. It is based on the default "Node.js v16" devcontainer preconfiguration.
You don't even need to forwardPorts anymore!
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.234.0/containers/javascript-node
{
"name": "My project",
"build": {
"dockerfile": "Dockerfile",
// Update 'VARIANT' to pick a Node version: 18, 16, 14.
// Append -bullseye or -buster to pin to an OS version.
// Use -bullseye variants on local arm64/Apple Silicon.
"args": { "VARIANT": "16" }
},
"settings": {},
"extensions": [
"dbaeumer.vscode-eslint"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "yarn install",
// Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "node"
}

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 ==='));
});

How to debug a Gulp task?

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');
});});

Gulp watch task does't exit on Ctrl C

Background
I am having this gulp watch task to handle sass compilation:
import gulp from 'gulp';
import sass from 'gulp-sass';
import concat from 'gulp-concat';
gulp.task("compile-scss", () => {
return gulp.src("assets/scss/**/*.scss")
.pipe(sass({ outputStyle: 'compressed' })
.on("error", sass.logError))
.pipe(concat("style.css"))
.pipe(gulp.dest("dist/css"));
});
gulp.task("watch-scss", ['compile-scss'], () => {
gulp.watch("assets/scss/**/*.scss", ["compile-scss"]);
});
I am then running gulp watch-scss and the process correctly compiles my files and start watching for new changes.
The problem
When I want watching to stop I am pressing Ctrl+C in the terminal and everything looks ok.
But then I make a change in the .scss file and expect it not be handled by the gulp task (should be already stopped). Anyway this change gets handled by the watch task as it seems still running.
Looking at the terminal code you can see where I start gulp watch-scss, where I press Ctrl+C and where task continues executing on change.
Environment details
OS: OS X 10.11 (El Capitan)
gulp version: 3.9.1
node version: 6.2.2
babel-core version: 6.11.4
History
The problem could be related to Node itself. Going into that direction I tried several solutions like terminating the process from within gulp like so:
process.on('SIGINT', function() {
process.exit();
});
It didn't help.
Read lot of info on that topic, but nothing helped. Here are two related questions, which didn't help either:
Stop a gulp watch task?
Terminate gulp-watch task
I can provide more details if needed.
Close the terminal and the session will be terminated. Run gulp again and try if CTRL + C works.

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.

Categories

Resources