How to use Nodejs to monitor file changes

Source: Internet
Author: User

1. Preface

When we debug code changes, every time we modify the code, even if only a small change, we need to manually rebuild the file, and then run the code to see the effect of the changes, this is particularly low efficiency, for developers can not tolerate.

2. Build the automatic compilation tool

How to use Nodejs to listen for file changes, and automatically run the build process once the source file is modified to save. For example, when you write Coffeescript file or sass file, the corresponding JS or CSS can be generated immediately after saving.

There are many modules for listening folder changes based on node. js.

A. Fs.watch. node. js's file system can also listen for changes in a directory

The biggest disadvantage of fs.watch is that it does not support the listening of subfolders, and in many cases hears two of events (many editors save the original file before saving it, so it triggers two folder change events). Therefore, some open source folders are required to listen for changes to the folder directory.

B. Chokidar. Chokidar is a node based . JS 's Listening folder change module

Step: 1. Run NPM install Chokidar--save-dev

NPM install [-g] Shelljs

2. Create a file Helper.js

3. Write in the Helper.js file:

var Chokidar = require (' Chokidar ');

var Shelljs = require (' Shelljs ');

Chokidar.watch (' accordion '). On (' Change ', function () {

' Use strict ';

Shelljs.exec ("Grunt build:accordion");

Shelljs.exec ("Node Helper.js");

Shelljs.exit (1); Quit when you're done.

});

In console output: node Helper.js can use Chokidar to monitor changes to our test.html files, here is the change of monitoring changes, once the test.html file has been modified and saved, then the console will output the statement: AAA.

Shelljs is used to execute commands

C. Watch. Watch is another node. JS module that changes the Listener folder

Like the usage of Chokidar, recommended Chokidar

How to use Nodejs to monitor file changes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.