Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watching './**/*.js' causes excessive CPU usage

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?

like image 252
Hedge Avatar asked Apr 25 '16 15:04

Hedge


2 Answers

gulp v3's watch had known CPU usage issues for almost 5 years. This is because gulp uses polling (fs.watchFile) to detect changes.

  • This has allegedly been fixed in gulp 4.0 (released Dec 2018), but there are reports of similar issues.
  • 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.

like image 59
josh3736 Avatar answered Oct 14 '22 09:10

josh3736


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']);
like image 45
Sven Schoenung Avatar answered Oct 14 '22 08:10

Sven Schoenung