Know if a file has changed its content with Node.js

2

On my server Node.js I would need to know if the content of a file has been modified, and if it is true, read it and send it by means of socket.io . The code I have, just reads the content the first time (when the page is reloaded).

init = function (server_created) {
    var listen = io.listen(server_created);
    listen.sockets.on('connection', function (socket) {
        myReadFile(socket);
    });
};

function myReadFile(socket) {
    fs.readFile(path, 'utf8', function (err, data) {
        if (err) {
            return console.log(err);
        }
    socket.emit('number', { number: data });
});
    
asked by Iván García 19.07.2017 в 21:16
source

3 answers

0
  

I would need to know if the content of a file has been modified.

For that you can read the metadata of the file, specifically the last modified field, which is accessed via mtime . It is also necessary to know the creation date ( ctime ).

const checkIfWasModified = (path) => (
  new Promise((resolve) => {
    fs.stat(path, (err, stats) => {
    const { ctime, mtime } = stats;
    if (ctime === mtime) {
      resolve(false);
    } else {
      resolve(true);
    }
  })
});

You just have to do:

const hasChanged = await checkIfWasModified('<ruta al archivo>');
if (hasChanged) { // ha cambiado, enviar el archivo }
else { // hacer otra cosa }
    
answered by 21.07.2017 в 04:25
0

First of all, on the server side we import fs#watch :

const { watch } = require('fs');

And we created the logic to issue the event to the users:

watch('./public/dummy.txt')
.addListener('change', (eventType, filename) => {
  //console.log(eventType, filename);
  io.emit('file:change');
});

Then on the client side, we hear the events connect and file:change .

  

Note: cache: 'no-store' serves to force a request to be made to the resource and prevent the resource contained in the cache from being used. Learn more .

<script type="text/javascript">
    console.log('window:load')
    const socket = io();

    async function loadFile(){
        console.log('file:change');
        let txt = await 
            fetch('http://localhost:3000/dummy.txt', { cache: 'no-store' })
            .then( res => res.text() );

        document.body.textContent = txt;
    }

    socket.on('connect', loadFile);
    socket.on('file:change', loadFile);
</script>

Answer a similar question in SO .

    
answered by 22.07.2017 в 17:43
0

Fs has a native method for that purpose, from modifying a file to knowing whether a folder / directory has been modified. I put the example code in your doc :

fs.watch('somedir', (eventType, filename) => {


 console.log('event type is: ${eventType}');
  if (filename) {
    console.log('filename provided: ${filename}');
  } else {
    console.log('filename not provided');
  }
});

Obviously you must import it.

You can now send the socket within the event

    
answered by 12.08.2017 в 00:02