简体   繁体   中英

npm watch with --filter option is not working

I am trying to use the npm watch to watch changes in a file and trigger another script in the package.json file.... but it is not working.

my watch script is as follows:

"watch": "watch 'npm run start' './src' --filter='./testFilter.js'"

The testFilter.js file is as follows, to watch the changes only in the testCode.js file:

 var watch = require('watch');

 watch.watchTree('./src/', function (f, curr, prev) {
    if (typeof f == "file" && prev === null && curr === null) {
      return("testCode.js");
    } else if (prev === null) {
      return("testCode.js");
    }
    return("testCode.js");
  })

When I am running the npm watch getting the following error.

/..../node_modules/watch/main.js:53
            if (options.filter && !options.filter(f, stat)) return done && callback(null, callback.files);
                                           ^

TypeError: options.filter is not a function
    at /.../node_modules/watch/main.js:53:44

I think the issue is in the above testFilter.js file... could you please provide a working code for this scenario? I just want to watch only a single file and run another script when that file is changed.

The documentation of the watch package says:

'filter' - You can use this option to provide a function that returns true or false for each file and directory to decide whether or not that file/directory is included in the watcher .

CLI USAGE:

    Usage: watch <command> […directory] [OPTIONS]


OPTION FILTER:

    --filter=<file>
        Path to a require-able .js file that exports a filter
        function to be passed to watchTreeOptions.filter.
        Path is resolved relative to process.cwd().

Example:

Here a working sample, it allow execution of the <command> defined to the watch command, in my case ( npm run assets:renameJs ), I want to rename the file dist/original.js to dist/renamed.js only when the dist/original.js file is changed.

This prevent a loop because without this filter, each time the file is renamed the watch is triggered.

// ./package.json

…
“scripts”: {
    …
    "assets:renameJs": "mv dist/original.js dist/renamed.js || true",
    "myWatch": "watch \"npm run assets:renameJs\" ./dist --filter='npm-watch-myFilter.js'"
}
…
// ./npm-watch-myFilter.js

/**
 * @param  {string} f Filename
 * @param  {object} stat File System @see {@link http://nodejs.org/api/fs.html File System}
 */
const myFilter = (f, stat) => stat.isFile() && f === 'dist/original.js';

module.exports = myFilter;

Links

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM