unpkg/server/middleware/MetadataUtils.js

58 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-05-25 18:25:42 +00:00
const fs = require('fs')
2017-08-11 06:12:22 +00:00
const path = require('path')
2017-05-25 18:25:42 +00:00
const { getContentType, getStats, getFileType } = require('./FileUtils')
2017-08-11 06:12:22 +00:00
function getEntries(dir, file, maximumDepth) {
return new Promise((resolve, reject) => {
fs.readdir(path.join(dir, file), (error, files) => {
2017-05-25 18:25:42 +00:00
if (error) {
reject(error)
} else {
resolve(
Promise.all(
2017-08-11 06:12:22 +00:00
files.map(function (f) {
return getStats(path.join(dir, file, f))
})
).then(function (statsArray) {
return Promise.all(statsArray.map(function (stats, index) {
return getMetadata(dir, path.join(file, files[index]), stats, maximumDepth - 1)
}))
})
2017-05-25 18:25:42 +00:00
)
}
})
})
2017-08-11 06:12:22 +00:00
}
2017-05-25 18:25:42 +00:00
2017-08-11 06:12:22 +00:00
function formatTime(time) {
return new Date(time).toISOString()
}
2017-05-25 18:25:42 +00:00
2017-08-11 06:12:22 +00:00
function getMetadata(dir, file, stats, maximumDepth) {
2017-05-25 18:25:42 +00:00
const metadata = {
lastModified: formatTime(stats.mtime),
2017-08-11 06:12:22 +00:00
contentType: getContentType(file),
path: file,
2017-05-25 18:25:42 +00:00
size: stats.size,
type: getFileType(stats)
}
if (!stats.isDirectory() || maximumDepth === 0)
return Promise.resolve(metadata)
2017-08-11 06:12:22 +00:00
return getEntries(dir, file, maximumDepth).then(function (files) {
2017-05-25 18:25:42 +00:00
metadata.files = files
return metadata
})
}
2017-08-11 06:12:22 +00:00
function generateMetadata(baseDir, path, stats, maximumDepth, callback) {
return getMetadata(baseDir, path, stats, maximumDepth).then(function (metadata) {
callback(null, metadata)
}, callback)
}
2017-05-25 18:25:42 +00:00
module.exports = {
2017-08-11 06:12:22 +00:00
get: generateMetadata
2017-05-25 18:25:42 +00:00
}