Persistence of "fs.watch"

1

I work in NodeJS , an acquaintance recommended me to do a watchdog (supervision) in which when a command is modified, it would be automatically reloaded (after being saved ). In the documentation of NodeJS I found the following:

link

However, I do not know what processes this does, that is, its persistence, if it checks if the files have been modified after periods of time, or only when the file has been modified instead of cycling.

Neither do I know if it would be the most efficient, I am open to suggestions.

Currently, I have the following code to load all the commands that are inside the / cmd / directory.

fs.readdir('./cmd/', (err, files) => {
    if(err) console.error(err);
    console.log(logwhite(
        'Loading a total of ' + loggreen(files.length) + ' commands.'
    ));
    const launch = new Date().getTime();
    files.forEach(f=> {
        let props = require('./cmd/${f}');
        var date = new Date().getTime();
        console.log(
            '${loggreen(date - launch)}ms   ' +
            loggray('Loading Command: ${props.help.name}        ') +
            loggreen(' Status OK')
        );
        bot.commands.set(props.help.name, props);
        props.conf.aliases.forEach(alias => {
            bot.aliases.set(alias, props.help.name);
        });
    });
});

Likewise, I have the following to reload a command, which I use reload {comando} :

let command;
if (bot.commands.has(params[0])) {
  command = params[0];
} else if (bot.aliases.has(params[0])) {
  command = bot.aliases.get(params[0]);
}
if (!command) {
  return msg.channel.sendMessage('I cannot find the command: ${params[0]}');
} else {
  msg.channel.sendMessage('Reloading: ${command}')
    .then(m => {
      bot.reload(command)
        .then(() => {
           m.edit('Successfully reloaded: ${command}');
        })
        .catch(e => {
           m.edit('Command reload failed: ${command}\n\'\'\'${e.stack}\'\'\'');
        });
    });
}

An acquaintance has advised me to use fs.watch , and my question was if fs.watch reviewed the changes periodically (revises them in a time interval), or revises the changes when a file has been modified (like a event).

What I want to do is, when a file has been modified, that a command similar to the one I have in reload {comando} is executed, that is, I modify a file, I save it, and the program automatically reloads it, without any need to use the reload command.

Is fs.watch the most efficient for this task? And if so, how should I use it?

    
asked by Antonio Roman 02.01.2017 в 16:57
source

1 answer

1

To use fs.watch just do this:

#!/usr/bin/env node
'use strict';

var fs = require('fs');
// var spawn = require('child_process').spawn;


(function start() {
    // aqui puedes cargar todos los comandos, tal cual lo haces al principio
})();

// pasas el archivo o directorio que quieras observar
const DIRECTORY = './cmd'
fs.watch(DIRECTORY, {encoding: 'buffer', recursive: true}, (eventType, fileName) => {
    // el primer parametro es el directorio que vigilirá
    // el segundo, es un objeto con el encoding, en este caso un buffer, y si va a ser recursivo(en sistemas basados en LINUX esta opcion no afecta, ver Nota)
    // el tercero, es el callback que recibe 2 argumentos

    if (eventType == 'change' && fileName) {
        // en este punto ya tienes el nombre del archivo, que puedes abrirlo con fs.readFile y hacer lo que quieras, o recargarlo como quieras.
        // en el caso que quieras recargar todos, puedes volver a llamar la funcion start();
    }
})

Note: The recursive parameter in the options only works in windows, so that the observer or watch can only observe files and folders that are at the level of the folder in which they are stored. listen, so if you have files in child folders to this directory, they will not have the event if you have a Linux.

I did not add the part of the processes, because I see that you are recharging the commands with a library (I do not know where that bot comes from), so I do not know many of the functions you have

    
answered by 02.01.2017 / 23:14
source