Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

loop through files in directory javascript

var fs = require('fs');
var path = require('path');
// In newer Node.js versions where process is already global this isn't necessary.
var process = require("process");

var moveFrom = "/home/mike/dev/node/sonar/moveme";
var moveTo = "/home/mike/dev/node/sonar/tome"

// Loop through all the files in the temp directory
fs.readdir(moveFrom, function (err, files) {
  if (err) {
    console.error("Could not list the directory.", err);
    process.exit(1);
  }

  files.forEach(function (file, index) {
    // Make one pass and make the file complete
    var fromPath = path.join(moveFrom, file);
    var toPath = path.join(moveTo, file);

    fs.stat(fromPath, function (error, stat) {
      if (error) {
        console.error("Error stating file.", error);
        return;
      }

      if (stat.isFile())
        console.log("'%s' is a file.", fromPath);
      else if (stat.isDirectory())
        console.log("'%s' is a directory.", fromPath);

      fs.rename(fromPath, toPath, function (error) {
        if (error) {
          console.error("File moving error.", error);
        } else {
          console.log("Moved file '%s' to '%s'.", fromPath, toPath);
        }
      });
    });
  });
});
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript try 
Javascript :: fetch in react 
Javascript :: docs where field exists 
Javascript :: error while connecting mongodb MongoParseError: option usefindandmodify is not supported 
Javascript :: javascript get elements that exist in two arrays 
Javascript :: how to remove a property from an object in javascript 
Javascript :: how to wait a determined amount of time before doing something in js 
Javascript :: get input type js 
Javascript :: npm md5 
Javascript :: js check if string is number 
Javascript :: MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 
Javascript :: mongoose id from string 
Javascript :: javascript sleep settimeout 
Javascript :: es6 remove empty property from object 
Javascript :: javascript index of min value in array 
Javascript :: javascript string comma seprated price to int 
Javascript :: alpine in laravel mix 
Javascript :: javascript get element tag 
Javascript :: discordjs eval 
Javascript :: insert item into array specific index javascript 
Javascript :: fetch javascript 
Javascript :: check for alphabetic string in javascript 
Javascript :: how to get selected value of dynamically created dropdown in jquery 
Javascript :: redux dev tools 
Javascript :: javascript add line from file to array 
Javascript :: find Array of value in JSON 
Javascript :: javascript remove final newline from string 
Javascript :: Javascript how to compare three numbers 
Javascript :: js add to array conditionally 
Javascript :: append HTML elements in JavaScript 
ADD CONTENT
Topic
Content
Source link
Name
2+6 =