unpkg/server/middleware/utils/getMetadata.js

78 lines
2.0 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')
const SRIToolbox = require('sri-toolbox')
2017-08-18 19:57:42 +00:00
const getFileContentType = require('./getFileContentType')
const getFileStats = require('./getFileStats')
const getFileType = require('./getFileType')
2017-05-25 18:25:42 +00:00
2017-08-11 06:12:22 +00:00
function getEntries(dir, file, maximumDepth) {
return new Promise(function (resolve, reject) {
fs.readdir(path.join(dir, file), function (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) {
2017-08-18 19:57:42 +00:00
return getFileStats(path.join(dir, file, f))
2017-08-11 06:12:22 +00:00
})
).then(function (statsArray) {
return Promise.all(statsArray.map(function (stats, index) {
return getMetadataRecursive(dir, path.join(file, files[index]), stats, maximumDepth - 1)
2017-08-11 06:12:22 +00:00
}))
})
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
function getIntegrity(file) {
return new Promise(function (resolve, reject) {
fs.readFile(file, function (error, data) {
if (error) {
reject(error)
} else {
resolve(SRIToolbox.generate({ algorithms: [ 'sha384' ] }, data))
}
})
})
}
function getMetadataRecursive(dir, file, stats, maximumDepth) {
2017-05-25 18:25:42 +00:00
const metadata = {
lastModified: formatTime(stats.mtime),
2017-08-18 19:57:42 +00:00
contentType: getFileContentType(file),
2017-08-11 06:12:22 +00:00
path: file,
2017-05-25 18:25:42 +00:00
size: stats.size,
type: getFileType(stats)
}
if (stats.isFile()) {
return getIntegrity(path.join(dir, file)).then(function (integrity) {
metadata.integrity = integrity
return metadata
})
}
2017-05-25 18:25:42 +00:00
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
})
}
function getMetadata(baseDir, path, stats, maximumDepth, callback) {
getMetadataRecursive(baseDir, path, stats, maximumDepth).then(function (metadata) {
2017-08-11 06:12:22 +00:00
callback(null, metadata)
}, callback)
}
2017-05-25 18:25:42 +00:00
2017-08-18 19:57:42 +00:00
module.exports = getMetadata