Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Skripten / Logik
    4. JavaScript
    5. Ordner auf neue Dateien überwachen

    NEWS

    • ioBroker@Smart Living Forum Solingen, 14.06. - Agenda added

    • ioBroker goes Matter ... Matter Adapter in Stable

    • Monatsrückblick - April 2025

    Ordner auf neue Dateien überwachen

    This topic has been deleted. Only users with topic management privileges can see it.
    • E
      ente34 @tomily last edited by

      @tomily
      Das geht leider nicht. Ich habe das Script mal erweitert,
      Du musst chkDirNotEmpty() oder chkDirTreeNotEmpty() benutzen, je nachdem, ob Du ein einzelnes Directory oder rekursiv den ganzen Baum absuchen willst

      const fs = require('fs');
      const util = require('util');
      const readdir = util.promisify(fs.readdir);
      const stat = util.promisify(fs.stat);
      const lstat = util.promisify(fs.lstat);
      
      const mountDir = '/home/pi/mount';
      const nasDir = '//nas02/backup/raspi-iobroker/backitup';
      const mountCmd = `sudo mount -t cifs -o username=rsync,password=...,vers=3.0 ${nasDir} ${mountDir}`;
      const umountCmd = `sudo umount ${nasDir}`;
      
      const warnSeconds = 5 * 86400;
      
      async function NewestFile(dir) {
          let newestFileAge = 0;
          let newestFile = '';
          //console.log('### '+dir);
          try {
              let files = [];
              files = await readdir(dir);
      
      
              for (let file of files) {
                  let fullpath = dir + '/' + file;
                  const s = await lstat(fullpath);
                  if (s.isFile()) {
                      const stats = await stat(fullpath);
                      if (stats.mtimeMs > newestFileAge) {
                          newestFileAge = stats.mtimeMs;
                          newestFile = file;
                      }
                  } else {
                      let values = await NewestFile(fullpath);
                      if (values.age > newestFileAge) {
                          newestFileAge = values.age;
                          newestFile = values.file;
                      }
                  }
              }
      
          } catch (e) {
              console.log(e);
          } finally {
              return { file: newestFile,  age:newestFileAge };
          }
      }
      
      async function chkDirNotEmpty(dir) {
          let files = await readdir(dir); 
          if ( files.length ){
              return files[0];
          }
          return "";
      }
      
      async function chkDirTreeNotEmpty(dir) {
          let foundFile = '';
          try {
              let files = [];
              files = await readdir(dir);
      
              for (let file of files) {
                  let fullpath = dir + '/' + file;
                  const s = await lstat(fullpath);
                  if (s.isFile()) {
                      foundFile = fullpath;
                      break;
                  } else {
                      let rc = await chkDirTreeNotEmpty(fullpath);
                      if (rc != "") {
                          foundFile = rc;
                          break;
                      }
                  }
              }
      
          } catch (e) {
              console.log(e);
          } finally {
              return foundFile;
          }
      }
      
      /**
       * Executes a shell command and return it as a Promise.
       * @param cmd {string}
       * @return {Promise<string>}
       */
      function execShellCommand(cmd) {
          const exec = require('child_process').exec;
          return new Promise((resolve, reject) => {
              exec(cmd, (error, stdout, stderr) => {
                  if (error) {
                      console.warn(error);
                  }
                  resolve(stdout ? stdout : stderr);
              });
          });
      }
      
      async function checkBackup() {
          try {
              //hier mount-Kommando
              await execShellCommand(mountCmd);
              
              //Nach leeren Directory suchen (nicht rekursiv, gefunden werden Files oder Directories)
              let file = await chkDirNotEmpty(mountDir);
              
              //Nach Files im Directory-Tree suchen (rekursiv)
              //file = await chkDirTreeNotEmpty(mountDir);
              if (file != "") {
                  console.log(`directory tree ${mountDir} not empty, found file "${file}" `);
                  // Mail abschicken
                  console.log('Send Mail');
      
              }
             
              let result = await NewestFile(mountDir);
              let seconds = (new Date().getTime() - new Date(result.age).getTime()) / 1000;
              if (seconds > warnSeconds) {
                  console.log(`newest file "${result.file}" created before ${seconds} seconds`);
                  // Mail abschicken
                  console.log('Send Mail');
              }
      
              //hier umount-Kommando
              await execShellCommand(umountCmd);
          } catch (e) {
              console.warn(e);
          }
      }
      
      // 22:30
      schedule('30 22 * * *', () => {
          checkBackup();
      });
      checkBackup();
      
      
      T 1 Reply Last reply Reply Quote 0
      • OliverIO
        OliverIO @tomily last edited by

        @tomily sagte in Ordner auf neue Dateien überwachen:

        Hallo zusammen,

        hat jemand eine Idee, wie ich folgendes realisieren kann?

        Ich möchte diverse Unterordner meiner NAS auf neue Dateien überprüfen.
        In den Ordnern liegen unterschiedlich viele Dateien und unterschiedliche Dateitypen.

        Ziel ist es, eine Email auszulösen, wenn die neueste Datei im Verzeichnis älter ist, als X-Tage.

        Damit möchte ich erreichen, dass mir zukünftig auffällt, wenn Datensicherungen nicht mehr erstellt werden.

        Hat jemand eine Idee oder zufällig schon ein fertiges Skript für diesen Monitoring-Zweck?

        Grüße

        Warum nimmst du nicht eine Standard Bibliothek von Node?
        Diese hat Cross Platform Support und funktioniert also für win linux und macos
        35 mio downloads pro Woche können nicht irren
        https://www.npmjs.com/package/chokidar

        1 Reply Last reply Reply Quote 0
        • T
          tomily @ente34 last edited by

          @ente34 Servus,
          ich danke Dir für deine Mühe und bitte herzlichst um Entschuldigung für meine späte Rückmeldung. Bin in den letzten Tagen umgezogen und war leider komplett offline.

          Hatte die vorgehenden Scripte etwas umgebaut, damit ich die Email auf meine Bedürfnisse anpassen kann. Du wirst schnell sehen, dass ich überhaupt kein guter Skripter bin, aber es hat funktioniert.

          Bei der neuen Variante bekomme ich die Email, auch wenn KEINE Datei im Ordner ist.

          Die Prüfung auf das Dateialter wäre mir dem Fall egal. Kann ich das dann einfach raus nehmen?
          Ich möchte nur prüfen, OB Dateien da sind oder Nicht. Das Alter der Dateien spielt für mich keine Rolle, deshalb habe ich es auf 0 gesetzt.

          Habe ich nun selbst einen Fehler eingebaut, oder wieso kommt die Mail jedes mal? 🤦 🐶

          // Skript zur Überprüfung von LEEREN bzw. NICHT-LEEREN VERZEICHNISSEN
          
          //Threshold - Dauer in Tagen
          var thresholdDays = 0;
          // Variable für Dateialter in Tagen. Wird weiter unten benutzt.
          var fileageDays = 0;
          // Variable für Dateinamen. Wird weiter unten benutzt.
          var newestFileName = 0;
          // Variable für "Jobname"
          var jobname = "VerzeichnissPruefung";
          
          const fs = require('fs');
          const util = require('util');
          const readdir = util.promisify(fs.readdir);
          const stat = util.promisify(fs.stat);
          const lstat = util.promisify(fs.lstat);
          
          
          // Mountbefehl zusammensetzen
          const mountDir = '/mnt/backupchecktemp';
          const nasDir = '//IP/PFAD'
          const mountCmd = `sudo mount -t cifs -o username=USERNAME,password=PASSWORT,vers=1.0 ${nasDir} ${mountDir}`;
          const umountCmd = `sudo umount ${nasDir}`;
          
          const warnSeconds = thresholdDays * 86400;
          
          async function NewestFile(dir) {
              let newestFileAge = 0;
              let newestFile = '';
              //console.log('### '+dir);
              try {
                  let files = [];
                  files = await readdir(dir);
           
          
                  for (let file of files) {
                      let fullpath = dir + '/' + file;
                      const s = await lstat(fullpath);
                      if (s.isFile()) {
                          const stats = await stat(fullpath);
                          if (stats.mtimeMs > newestFileAge) {
                              newestFileAge = stats.mtimeMs;
                              newestFile = file;
                          }
                      } else {
                          let values = await NewestFile(fullpath);
                          if (values.age > newestFileAge) {
                              newestFileAge = values.age;
                              newestFile = values.file;
                          }
                      }
                  }
           
          
              } catch (e) {
                  console.log(e);
              } finally {
                  return { file: newestFile,  age:newestFileAge };
              }
          }
           
          
          async function chkDirNotEmpty(dir) {
              let files = await readdir(dir); 
              if ( files.length ){
                  return files[0];
              }
              return "";
          }
           
          
          async function chkDirTreeNotEmpty(dir) {
              let foundFile = '';
              try {
                  let files = [];
                  files = await readdir(dir);
           
          
                  for (let file of files) {
                      let fullpath = dir + '/' + file;
                      const s = await lstat(fullpath);
                      if (s.isFile()) {
                          foundFile = fullpath;
                          break;
                      } else {
                          let rc = await chkDirTreeNotEmpty(fullpath);
                          if (rc != "") {
                              foundFile = rc;
                              break;
                          }
                      }
                  }
           
          
              } catch (e) {
                  console.log(e);
              } finally {
                  return foundFile;
              }
          }
          
          
          
          /**
           * Executes a shell command and return it as a Promise.
           * @param cmd {string}
           * @return {Promise<string>}
           */
          
          function execShellCommand(cmd) {
              const exec = require('child_process').exec;
              return new Promise((resolve, reject) => {
                  exec(cmd, (error, stdout, stderr) => {
                      if (error) {
                          console.warn(error);
                      }
                      resolve(stdout ? stdout : stderr);
                  });
              });
          }
           
          
          async function checkBackup() {
              try {
                  //hier mount-Kommando
                  await execShellCommand(mountCmd);
                
                  //Nach leeren Directory suchen (nicht rekursiv, gefunden werden Files oder Directories)
                  //let file = await chkDirNotEmpty(mountDir);
             
                  //Nach Files im Directory-Tree suchen (rekursiv)
                  //file = await chkDirTreeNotEmpty(mountDir);
                  //if (file != "") {
                  //    console.log(`directory tree ${mountDir} not empty, found file "${file}" `);
                      // Mail abschicken
                  //    console.log('Send Mail');
                  //}
          
          
                  let result = await NewestFile(mountDir);
                  let seconds = (new Date().getTime() - new Date(result.age).getTime()) / 1000;
          		// Dateialter in Tagen ausrechnen und in Variable übergeben
                  (fileageDays = (seconds / 86400))
                  newestFileName = result.file
          		if (seconds > warnSeconds) {
                      console.log(`newest file "${result.file}" created before ${seconds} seconds`);
                      // Mail abschicken
          			console.log('Send Mail');
          			sendTo("email.0", "send", {
          				text: "Directorycheck: " + jobname + "\nLetzte Datei: " + newestFileName + " \nAlter der Datei: " + fileageDays.toFixed(1) + " Tage \nThreshold: " + thresholdDays + " Tage" + "\nVerzeichnis: " + nasDir,
          				to: 'monitoring@tomkeierleber.de',
          				subject: 'Monitoring // Neue Dateien gefunden: ' + jobname
          				});
          						
                  }
          
          
                  //hier umount-Kommando
                  await execShellCommand(umountCmd);
              } catch (e) {
                  console.warn(e);
              }
          }
          
          // Time scheduler
          schedule('05 16 * * *', () => {
              checkBackup();
          });
          checkBackup();
          
           
          
          
          E 1 Reply Last reply Reply Quote 0
          • E
            ente34 @tomily last edited by

            @tomily
            Ich muss noch einmal nachfragen, wann möchtest Du bei der neuen Variante eine Nachricht bekommen?
            Willst Du beide Varianten für verschiedene Directories gleichzeitig benutzen?

            T 1 Reply Last reply Reply Quote 0
            • T
              tomily @ente34 last edited by

              @ente34 Dieser Anwendungsfall wäre:

              Benachrichtigung, wenn Ordner NICHT Leer ist.

              Es handelt sich also beispielsweise um ein Verzeichnis, das immer leer sein sollte. Sobald es nicht mehr leer ist (Inhalt y >= 1 Datei), dann wird die Benachrichtigung ausgelöst.

              Keine Sorge, die anderen Skripte waren nicht um sonst und sind beide fleißig im Einsatz.
              Beim Einsetzen und anpassen ist mir diese Anwendungsart noch eingefallen und wäre sehr hilfreich.

              Grüße

              E 1 Reply Last reply Reply Quote 0
              • E
                ente34 @tomily last edited by

                @tomily
                Du musst nur folgendes einkommentieren (ev. anderen Pfad statt mountDir benutzen)

                        //Nach leeren Directory suchen (nicht rekursiv, gefunden werden Files oder Directories)
                        let file = await chkDirNotEmpty(mountDir);
                        if (file != "") {
                            console.log(`directory tree ${mountDir} not empty, found file "${file}" `);
                            // Mail abschicken
                            console.log('Send Mail');
                        }
                
                
                T 1 Reply Last reply Reply Quote 0
                • T
                  tomily @ente34 last edited by

                  @ente34
                  GEIL!

                  GEIL! 🙂

                  Es ist manchmal so einfach. Habe den falschen Bereich auskommentiert, weil ich den Code nicht 100%ig verstanden hab.
                  Durch deine erneute und geduldige Hilfe bin ich erneut am Ziel 🙂

                  Mega cool....auch das funktioniert nun genau wie gewünscht 😃

                  Grüße
                  Tomily

                  1 Reply Last reply Reply Quote 0
                  • M
                    michihorn @AlCalzone last edited by

                    @alcalzone sagte in Ordner auf neue Dateien überwachen:

                    Wenn es wirklich nur um neue Dateien (neuer Name, nicht überschrieben) geht, kann man im JS Skript auch lediglich mtime des Verzeichnisses prüfen und muss nicht erst alle Dateien enumerieren und deren Zeitstempel prüfen.

                    Hast du ein Beispiel dazu, ich möchte gerne ein Verzeichnis auf meiner Fritzbox.NAS lesen können
                    Gruß
                    Michael

                    AlCalzone 1 Reply Last reply Reply Quote 0
                    • AlCalzone
                      AlCalzone Developer @michihorn last edited by

                      @michihorn Öhh...

                      const fs = require("fs");
                      const mtime = fs.statSync("/pfad/des/verzeichnisses").mtime;
                      
                      if (mtime > /* Zeitstempel */) {
                        // reagieren
                      }
                      
                      1 Reply Last reply Reply Quote 0
                      • A
                        abuzze @ente34 last edited by

                        @ente34 sagte in Ordner auf neue Dateien überwachen:

                        @tomily

                        Ungefähr so
                        Du benötigst aber den neuesten javascript-Adapter 4.11.0

                        const fs = require('fs');
                        const util = require('util');
                        const readdir = util.promisify(fs.readdir);
                        const stat = util.promisify(fs.stat);
                        const lstat = util.promisify(fs.lstat);
                        
                        async function checkDir(dir) {
                            let files = [];
                            try {
                                files = await readdir(dir);
                               
                                let newestFileAge = 0;
                                let newestFile = '';
                        
                                for (let file of files) {
                                    let fullpath = dir + '/' + file;
                                    const s = await lstat(fullpath);
                                    if (s.isFile()) {
                                        const stats = await stat(fullpath);
                                        if (stats.mtimeMs > newestFileAge) {
                                            newestFileAge = stats.mtimeMs;
                                            newestFile = file;
                                        }
                                    }
                                }
                        
                                let seconds = (new Date().getTime() - new Date(newestFileAge).getTime()) / 1000;
                                console.log(`newest file "${newestFile}" created before ${seconds} seconds`);
                            } catch (e) {
                                console.log(e);
                            }
                        }
                        
                        checkDir('c:/temp');
                        
                        

                        Hallo in die Runde.
                        Ist schon ein bisschen älter das Thema aber ich habe dazu noch eine Frage.
                        Was muss ich an diesem Code ändern, damit ich auch Unterverzeichnisse auf neuste Dateien prüfen kann ?
                        Danke

                        1 Reply Last reply Reply Quote 0
                        • First post
                          Last post

                        Support us

                        ioBroker
                        Community Adapters
                        Donate

                        1.1k
                        Online

                        31.7k
                        Users

                        79.7k
                        Topics

                        1.3m
                        Posts

                        8
                        37
                        3686
                        Loading More Posts
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes
                        Reply
                        • Reply as topic
                        Log in to reply
                        Community
                        Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen
                        The ioBroker Community 2014-2023
                        logo