Created
April 3, 2018 14:50
-
-
Save egoarka/1d0d3bc88aab5d92b8b58aa98da7f57d to your computer and use it in GitHub Desktop.
load_json_files_from_directory.js
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
const { promisify } = require("util"); | |
const { resolve } = require("path"); | |
const fs = require("fs"); | |
const readdir = promisify(fs.readdir); | |
const rename = promisify(fs.rename); | |
const stat = promisify(fs.stat); | |
const readfile = promisify(fs.readFile); | |
async function getFiles(dir) { | |
const subdirs = await readdir(dir); | |
const files = await Promise.all( | |
subdirs.map(async subdir => { | |
const res = resolve(dir, subdir); | |
return (await stat(res)).isDirectory() ? getFiles(res) : res; | |
}) | |
); | |
return files.reduce((a, f) => a.concat(f), []); | |
} | |
const jsonOnly = files => files.filter(file => file.match(/\.json?$/i)); | |
const fileToJson = async file => { | |
const content = await readfile(file); | |
return JSON.parse(content); | |
}; | |
(async () => { | |
const filePaths = await getFiles("."); | |
const jsonFilePaths = jsonOnly(filePaths); | |
const contents = await Promise.all(jsonFilePaths.map(fileToJson)); | |
console.log(contents); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment