지정한 경로의 파일 변경 감지 ➔ 명령 실행하는 방법.

1. fswatch

공식 웹사이트

A cross-platform file change monitor with multiple backends: Apple OS X File System Events API, *BSD kqueue, Solaris/Illumos File Events Notification, Linux inotify, Microsoft Windows and a stat()-based backend.

*nix(+ WSL) 및 Windows 용

설치

# macOS
brew install fswatch
    
# Debian/Ubuntu
sudo apt-get install fswatch
    
# Windows (Scoop)
scoop install fswatch

예제

# bash
 
# 'src' 경로 하위 파일 변경을 감시하여, 변경시 build.sh 실행
# -o: 순간적으로 발생한 다수 이벤트를 하나로 처리
fswatch -o src | while read -r file; do
  echo "Change detected in ${file}."
  ./scripts/build.sh
done

2. chokidar-cli (node)

npm 패키지 페이지

Fast cross-platform command line utility to watch file system changes.
The underlying watch library is Chokidar, which is one of the best watch utilities for Node. Chokidar is battle-tested:

VS Code, Webpack 등에서 사용중인 라이브러리. node 프로젝트에서 자체 watcher 구축시 유용함.

설치

설치
npm install chokidar-cli --save-dev

사용법

문법: chokidar <patterns> -c '<command>'

chokidar "src/**/*.js" -c "./scripts/build.sh"

예제

  • debounce: 지정한 ms 이내 발생한 이벤트를 하나로 처리
npx chokidar-cli "**/*.ts" \  
    --ignore "node_modules/**" \  
    --ignore "**/@obsolete/**" \  
    --debounce 1000 \  
    -c "bash build.sh"

3. nodemon (node)

npm 패키지 페이지

nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.

nodemon does not require any additional changes to your code or method of development. nodemon is a replacement wrapper for node. To use nodemon, replace the word node on the command line when executing your script.

원래 node.js 프로젝트에서 소스코드 변경시 서버 재시작용으로 만들어진 node 명령 wrapper 이나, 임의 파일 모니터링 ➔ 임의 파일 실행 용도로도 사용 가능.

설치

설치
npm install nodemon --save-dev

사용법

nodemon --watch src --e ts,json --ignore 'obsolete/*.js' --ignore '**/test/**' \
        --exec "./scripts/build.sh"