Created
January 21, 2020 07:39
-
-
Save kuanhsuh/a336490d5f4b8ae9236c31cbe8b0e2d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 dirName = "/Users/dannyhuang/Downloads"; | |
fs.mkdirSync(`${dirName}/images`, { recursive: true }); | |
fs.mkdirSync(`${dirName}/documents`, { recursive: true }); | |
fs.mkdirSync(`${dirName}/pdf`, { recursive: true }); | |
fs.mkdirSync(`${dirName}/media`, { recursive: true }); | |
fs.mkdirSync(`${dirName}/other`, { recursive: true }); | |
// Loop through all the files in the temp directory | |
fs.readdir(dirName, function(err, files) { | |
if (err) { | |
console.error("Could not list the directory.", err); | |
process.exit(1); | |
} | |
files.forEach(function(file, index) { | |
console.log(path.extname(file)); | |
if (path.extname(file) === ".pdf") { | |
let fromPath = path.join(dirName, file); | |
let toPath = path.join(`${dirName}/pdf`, file); | |
fs.rename(fromPath, toPath, function(error) { | |
if (error) { | |
console.error("File moving error.", error); | |
} else { | |
console.log("Moved file '%s' to '%s'.", fromPath, toPath); | |
} | |
}); | |
} | |
if (path.extname(file) === ".jpg" || path.extname(file) === ".png") { | |
let fromPath = path.join(dirName, file); | |
let toPath = path.join(`${dirName}/images`, file); | |
fs.rename(fromPath, toPath, function(error) { | |
if (error) { | |
console.error("File moving error.", error); | |
} else { | |
console.log("Moved file '%s' to '%s'.", fromPath, toPath); | |
} | |
}); | |
} | |
if (path.extname(file) === ".mp3" || path.extname(file) === ".mp4") { | |
let fromPath = path.join(dirName, file); | |
let toPath = path.join(`${dirName}/media`, file); | |
fs.rename(fromPath, toPath, function(error) { | |
if (error) { | |
console.error("File moving error.", error); | |
} else { | |
console.log("Moved file '%s' to '%s'.", fromPath, toPath); | |
} | |
}); | |
} | |
if ( | |
path.extname(file) === ".xlsx" || | |
path.extname(file) === ".csv" || | |
path.extname(file) === ".docx" | |
) { | |
let fromPath = path.join(dirName, file); | |
let toPath = path.join(`${dirName}/documents`, file); | |
fs.rename(fromPath, toPath, function(error) { | |
if (error) { | |
console.error("File moving error.", error); | |
} else { | |
console.log("Moved file '%s' to '%s'.", fromPath, toPath); | |
} | |
}); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment