How can I run a Node.js app using grunt-contrib-watch? - node.js

For example, I have a project folder "myProject" with the following files:
/myProject/app.js
/myProject/foo.json
Is there a way to setup grunt-contrib-watch to run app.js any time foo.json is modified?

Something like:
shell: {
runapptask: {
command: [
'node /myPorject/app.js'
]
}
},
watch: {
runapp: {
files: ['/myproject/foo.json'],
tasks: ['shell:runapptask']
}
}

Related

How to execute npm script using grunt-run?

I have a npm task in my package.json file as follows to execute jest testing:
"scripts": {
"test-jest": "jest",
"jest-coverage": "jest --coverage"
},
"jest": {
"testEnvironment": "jsdom"
},
I want to execute this task npm run test-jest using grunt. I installed grunt-run for the same and added the run task, but how do I invoke this npm task there?
run: {
options: {
// Task-specific options go here.
},
your_target: {
cmd: 'node'
}
}
Configure your Gruntfile.js similar to the example shown in the docs.
Set the value for the cmd to npm.
Set run and test-jest in the args Array.
Gruntfile.js
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-run');
grunt.initConfig({
run: {
options: {
// ...
},
npm_test_jest: {
cmd: 'npm',
args: [
'run',
'test-jest',
'--silent'
]
}
}
});
grunt.registerTask('default', [ 'run:npm_test_jest' ]);
};
Running
Running $ grunt via your CLI using the configuration shown above will invoke the npm run test-jest command.
Note: Adding --silent (or it's shorthand equivalent -s) to the args Array simply helps avoids the additional npm log to the console.
EDIT:
Cross Platform
Using the grunt-run solution shown above failed on Windows OS when running via cmd.exe. The following error was thrown:
Error: spawn npm ENOENT Warning: non-zero exit code -4058 Use --force to continue.
For a cross-platform solution consider installing and utlizing grunt-shell to invoke the npm run test-jest instead.
npm i -D grunt-shell
Gruntfile.js
module.exports = function (grunt) {
require('load-grunt-tasks')(grunt); // <-- uses `load-grunt-tasks`
grunt.initConfig({
shell: {
npm_test_jest: {
command: 'npm run test-jest --silent',
}
}
});
grunt.registerTask('default', [ 'shell:npm_test_jest' ]);
};
Notes
grunt-shell requires load-grunt-tasks for loading the Task instead of the typical grunt.loadNpmTasks(...), so you'll need to install that too:
npm i -D load-grunt-tasks
For older version of Windows I had to install an older version of grunt-shell, namely version 1.3.0, so I recommend installing an earlier version.
npm i -D grunt-shell#1.3.0
EDIT 2
grunt-run does seem to work on Windows if you use the exec key instead of the cmd and args keys...
For cross platform purposes... I found it necessary to specify the command as a single string using the exec key as per the documentation that reads:
If you would like to specify your command as a single string, useful
for specifying multiple commands in one task, use the exec: key
Gruntfile.js
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-run');
grunt.initConfig({
run: {
options: {
// ...
},
npm_test_jest: {
exec: 'npm run test-jest --silent' // <-- use the exec key.
}
}
});
grunt.registerTask('default', [ 'run:npm_test_jest' ]);
};

How to run Grunt Copy Task automatically when our project run

I want to copy some files from one folder to another automatically when my project start.Now I do it by run a command in cmd "grunt copy". Please help me on this.
My Gruntfile.js Code:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
copy: {
t1: {
src: 'Scripts/**',
dest:'Target/'
}
}
});
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.registerTask('default', 'copy:t1');
};
I think you need to have grunt.registerTask('default', ['copy:t1']);

How to prevent grunt-nodemon from restarting all apps

I'm running node on Windows 10. I have three node apps and I want to be able to start them all up with one handy grunt command. Furthermore, I want node to automatically restart if I modify any of the apps.
I'm using a combination of grunt-nodemon and grunt-concurrent for this. The node processes all start up fine.
The problem is that if I modify the code related to any of them they all restart, which takes a long time. How can I make it so that nodemon only restarts the app whose code I actually modified?
var loadGruntTasks = require('load-grunt-tasks')
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concurrent: {
runAll: {
tasks: ['nodemon:app1', 'nodemon:app2', 'nodemon:app3'],
options: {
logConcurrentOutput: true
}
}
},
nodemon: {
app1: {
script: './app1/app.js'
},
app2: {
script: './app2/app.js'
},
app3: {
script: './app3/app.js'
}
}
})
loadGruntTasks(grunt)
grunt.registerTask('default', ['concurrent:runAll'])
}
Update
If I use grunt-watch instead of grunt-nodemon, only the app whose code I modified will restart. The problem is that grunt-watch only knows to run node app.js which gives an error because the app is already running. Is there a way to make grunt-watch kill the node process and restart it?
I think the answer could be fairly simple. Nodemon has an ignore option. For each of your three applications nodemon grunt configurations you can configurate them to ignore the directories of the other applications. That way they only kick off their restart when their own files are changed and not those of other projects. Let me know how that goes. :) Specifics about setting up the ignore section of config can be found in both nodemons documentation and grunt-nodemons documentation.
Patrick Motard's answer made me think about what directory nodemon was running in and how it was observing the files for changes. It appears that since I started grunt inside the parent directory of all the node apps that each nodemon process was looking for changes in all of those directories. So I set the working directory of the nodemon processes to the corresponding directory for each app using the options.cwd setting. That seemed to fix it. Here is the working solution:
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concurrent: {
runAll: {
tasks: ['nodemon:app1', 'nodemon:app2', 'nodemon:app3'],
options: {
logConcurrentOutput: true
}
}
},
nodemon: {
app1: {
script: 'app.js',
options: {
cwd: './app1'
}
},
app2: {
script: 'app.js',
options: {
cwd: './app2'
}
},
app3: {
script: 'app.js',
options: {
cwd: './app3'
}
}
}
})
loadGruntTasks(grunt)
grunt.registerTask('default', ['concurrent:runAll'])
}

Grunt concurrent task outputting nothing

I want my Grunt based setup to run both "test" (i.e. the unit tests) and "server" (i.e. the web server) at the same time, so that I can just do grunt testAndServer to run both (and update both when any file is changed) in the same terminal.
Code (much of it is based on the yo angular scaffold):
// in initConfig:
concurrent: {
testAndWebServer: [
'karma',
'watch'
]
},
and later
grunt.registerTask('testAndServer', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'concurrent:server',
'autoprefixer',
'compass',
'connect:livereload',
'open',
'concurrent:testAndWebServer'
]);
});
This actually works, but I don't get any output in the terminal (PowerShell) window. I would like the karma task to show the results of the tests. How can I acheive that?
I am running Node.js v0.10.20 on Windows 7, on a quadcore machine.
I just realized that I missed the logConcurrentOutput option.
This makes it work:
testAndWebServer: {
tasks: ['watch', 'karma'],
options: { logConcurrentOutput: true }
},

Grunt watch: compile only one file not all

I have grunt setup to compile all of my coffee files into javascript and maintain all folder structures using dynamic_mappings which works great.
coffee: {
dynamic_mappings: {
files: [{
expand: true,
cwd: 'assets/scripts/src/',
src: '**/*.coffee',
dest: 'assets/scripts/dest/',
ext: '.js'
}]
}
}
What I would like to do is then use watch to compile any changed coffee file and still maintain folder structure. This works using the above task with this watch task:
watch: {
coffeescript: {
files: 'assets/scripts/src/**/*.coffee',
tasks: ['coffee:dynamic_mappings']
}
}
The problem is that when one file changes it compiles the entire directory of coffee into Javascript again, it would be great if it would only compile the single coffee file that was changed into Javascript. Is this naturally possible in Grunt or is this a custom feature. The key here is it must maintain the folder structure otherwise it would be easy.
We have custom watch scripts at work and I'm trying to sell them on Grunt but will need this feature to do it.
You can use something like the following Gruntfile. Whenever a CoffeeScript file changes, it updates the configuration for coffee:dynamic_mappings to only use the modified file as the src.
This example is a slightly modified version of the example in the grunt-contrib-watch readme.
Hope it helps!
var path = require("path");
var srcDir = 'assets/scripts/src/';
var destDir = 'assets/scripts/dest/';
module.exports = function( grunt ) {
grunt.initConfig( {
coffee: {
dynamic_mappings: {
files: [{
expand: true,
cwd: srcDir,
src: '**/*.coffee',
dest: destDir,
ext: '.js'
}]
}
},
watch : {
coffeescript : {
files: 'assets/scripts/src/**/*.coffee',
tasks: "coffee:dynamic_mappings",
options: {
spawn: false, //important so that the task runs in the same context
}
}
}
} );
grunt.event.on('watch', function(action, filepath, target) {
var coffeeConfig = grunt.config( "coffee" );
// Update the files.src to be the path to the modified file (relative to srcDir).
coffeeConfig.dynamic_mappings.files[0].src = path.relative(srcDir, filepath);
grunt.config("coffee", coffeeConfig);
} );
grunt.loadNpmTasks("grunt-contrib-coffee");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.registerTask("default", [ "coffee:dynamic_mappings", "watch:coffeescript"]);
};
found a solution from an answer to a similar question https://stackoverflow.com/a/19722900/1351350
short answer: try https://github.com/tschaub/grunt-newer

Resources