Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs re-import file when it changes

My main code is under chokidar watched folder, when a file changes it emit an event

The main script is this

const fileName = "test.ts";
import(fileName).then((t: any) => {
  t.default();
});

and this is the file test.ts

export default () => {
  console.log("aaa");
};

I need to reimport file when I change test.ts, for example, I need this

START script

OUTPUT "aaa"

CHANGE test.ts from "console.log("aaa")" to "console.log("bbb")"

OUTPUT "bbb"

like image 330
Mauro Sala Avatar asked Nov 06 '22 22:11

Mauro Sala


1 Answers

The solution is to use decache, full code is this (with chokidar folder watcher)

const folder = chokidar.watch("./myFolder", {
    ignored: /(^|[\/\\])\../,
    persistent: true,
});
folder
.on("add", (fileName: string) => {
    const mod = require(fileName)
    mod.default();
.on("change", (fileName: string) => {
    decache(fileName);
    const mod = require(fileName)
    mod.default();
})
like image 98
Mauro Sala Avatar answered Nov 10 '22 01:11

Mauro Sala