bahixa4869
bahixa4869

Reputation: 21

Node.js package script that runs every time a file is changed

I'm developing a node.js package that generates some boilerplate code for me.

I was able to create this package and if I run every module individual it works fine and generates the code as expected.

My idea now is to import this package in another project and have it generate the code.

I have no idea to how to achieve this or even if it's possible.

The perfect solution would be that every time a file changed in a set of folders it would run the package and generate the files but if this isn't possible it would be ok as well to expose or command to manually generate this files.

I have created a script to run the generator script but it only works on the package itself and not when I import it in another project.

Thanks

Upvotes: 1

Views: 670

Answers (1)

O. Jones
O. Jones

Reputation: 108641

I think you want the fs.watch() function. It invokes a callback when a file (or directory) changes.

import { watch } from 'fs';

function watchHandler (eventType, filename) {
  console.log(`event type is: ${eventType}`)  /* 'change' or 'rename' */
  if (filename) {
    console.log(`filename provided: ${filename}`)
  } else {
    console.log('filename not provided');
  }
}

const options = { persistent: true }

const watcher = fs.watch('the/path/you/want', options, watchHandler)
...
watcher.close()

You can use this from within your nodejs app to invoke watchHandler() for each file involved in your code generation problem.

Upvotes: 1

Related Questions