DEV Community

Krzysztof Żuraw
Krzysztof Żuraw

Posted on • Originally published at krzysztofzuraw.com on

2 2

Run script on files changes using nodemon

I recently was setting up workflow for developing email templates and I need a way to copy files from src directory into dist build folder. It turns out that you can use for this nodemon. Script below is using glob library to watch for all .txt files under source directory and copy them from to build output directory. In addition to that it flattens the path - so if file is under src/plaintext/plaintext.txt the path in output will be dist/plaintext.txt.

import { copyFileSync, existsSync, mkdirSync } from "fs";
import glob from "glob";
import { basename, join } from "path";

const directory = "dist";

if (!existsSync(directory)) {
  mkdirSync(directory);
}

glob("src/**/*.txt", (err, files) => {
  if (err) {
    console.error("Error", err);
  }

  files.forEach((file) => {
    copyFileSync(file, join(directory, basename(file)));
  });
});
Enter fullscreen mode Exit fullscreen mode

How to run this script? I' using nodemon copy-plaintext.mjs --ext txt --watch src command in my package.json. It looks for all files with txt extension under src folder - if they change I'm running copy-plaintext.mjs.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more