I need to watch all folders including the current one for changes. Therefore I used
gulp.task('start', () => {
if (node) node.kill()
node = spawn('node', ['server.js'], {
stdio: 'inherit'
})
node.on('close', function(code) {
if (code === 8) {
gulp.log('Error detected, waiting for changes...');
}
});
});
gulp.watch(['./**/*.js'], ['start']);
gulp.task('default', ['start', 'watch']);
process.on('exit', function() {
if (node) node.kill()
});
but it causes 100% CPU usage. If I use it only on a single folder (which contains 99% of all files which need to be watched) like 'api/**/*.js` there's hardly any CPU usage.
What am I doing wrong?
gulp v3's watch
had known CPU usage issues for almost 5 years. This is because gulp uses polling (fs.watchFile
) to detect changes.
For versions < 4, the workaround recommendation is to increase the polling interval.
gulp.watch('**/*.js', { interval: 2000 }, ...)
(the default is 100)
@Sven's advice is also very sound -- there's likely no reason to watch your node_modules or build folders.
You are watching all .js
files in all directories and subdirectories of your project. Which includes node_modules
. Depending on how many dependencies you have in your project and how many dependencies those dependencies have etc. you might be watching thousands of .js
files.
You should limit your watch glob to only those directories where source files are located:
gulp.watch(['api/**/*.js', 'app/**/*.js', ...], ['start']);
Alternatively you can try to exclude your node_modules
folder and any other folders that don't contain source files (like your build destination folder):
gulp.watch(['api/**/*.js', '!node_modules/**/*.js', ...], ['start']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With