Skip to content

Instantly share code, notes, and snippets.

@justusbluemer
Created December 2, 2019 15:53
Show Gist options
  • Save justusbluemer/5102b5be6a985ecfa094d06a1866d291 to your computer and use it in GitHub Desktop.
Save justusbluemer/5102b5be6a985ecfa094d06a1866d291 to your computer and use it in GitHub Desktop.
Loads files from a directory and parses them as JSON
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