Created
December 2, 2019 15:53
-
-
Save justusbluemer/5102b5be6a985ecfa094d06a1866d291 to your computer and use it in GitHub Desktop.
Loads files from a directory and parses them as JSON
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 fs = require("fs") | |
;(async function() { | |
let items = await loadJSONFiles("items/") | |
console.log(items) | |
})() | |
/** | |
* Loads and parses JSON files from the specified directory | |
* @param {string} dirname The name of the directory | |
* @return {array} One array per file containing the parsed JSON object | |
*/ | |
async function loadJSONFiles(dirname) { | |
return new Promise((resolve, reject) => { | |
fs.readdir(dirname, function(err, filenames) { | |
if (err) { | |
onError(err) | |
return | |
} | |
var files = [] | |
filenames.forEach(function(filename) { | |
files.push( | |
new Promise((resolve, reject) => { | |
fs.promises | |
.readFile(dirname + filename, "utf-8") | |
.then(json => { | |
resolve(JSON.parse(json)) | |
}) | |
}) | |
) | |
}) | |
resolve(Promise.all(files)) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment