Created
April 28, 2021 15:02
-
-
Save itsMapleLeaf/8bc0c5fa727fa7ee8a0ab9397f12483a to your computer and use it in GitHub Desktop.
node code cleanup
This file contains hidden or 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
const fs = require("fs") | |
const fsPromises = require("fs/promises") | |
;(async () => { | |
try { | |
// passing utf-8 here (the encoding argument) makes it return a string | |
const fileList = await fsPromises.readFile("./exclude", "utf-8") | |
const excludeList = fileList.split("\n") | |
const allFileList = await fsPromises.readdir("./") | |
const finalFileList = allFileList.filter((file) => { | |
if (excludeList.includes(file)) return false | |
if (file.indexOf(".") == 0) return false | |
if (file.split(".").length == 1) return false | |
return true | |
}) | |
// this works because async functions return a promise, | |
// so we map `finalFileList` to a list of promises, | |
// then await them all in parallel via Promise.all | |
await Promise.all( | |
finalFileList.map(async (file) => { | |
const extension = file.split(".")[1] | |
// if you pass `{ recursive: true }` to mkdir, | |
// it'll create the directory if it exists, but do nothing otherwise | |
await fsPromises.mkdir(`./${extension}`, { recursive: true }) | |
await fsPromises.rename(file, `./${extension}/${file}`) | |
console.log(`File ${file} moved successfully`) | |
}) | |
) | |
} catch (error) { | |
// the error stack is generally more useful than just the message | |
// but we also fall back to the message in case there is no stack | |
console.log(error.stack || error.message || error) | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment