56 lines
1.8 KiB
JavaScript
56 lines
1.8 KiB
JavaScript
'use strict';
|
|
|
|
const config = require('config');
|
|
const fs = require('fs-extra');
|
|
const path = require('path');
|
|
const truncate = require('../utils/truncate-bytes');
|
|
const logger = require('../logger')(__filename);
|
|
|
|
function limitPathElement(element, limit) {
|
|
return element.split('/').map((component) => {
|
|
if (config.library.truncate && Buffer.from(component).length > limit) {
|
|
return truncate(component, limit - config.library.truncate.truncator.length) + config.library.truncate.truncator;
|
|
}
|
|
|
|
return component;
|
|
}).join(path.sep);
|
|
}
|
|
|
|
function getPathElements(requestedFilepath) {
|
|
const originalPathElements = path.parse(requestedFilepath);
|
|
|
|
return {
|
|
root: originalPathElements.root,
|
|
dir: limitPathElement(originalPathElements.dir, config.library.truncate.limit),
|
|
name: limitPathElement(originalPathElements.name, config.library.truncate.limit - originalPathElements.ext.length),
|
|
ext: originalPathElements.ext,
|
|
};
|
|
}
|
|
|
|
async function writeBufferToFile(target, buffer, item) {
|
|
await fs.writeFile(target, buffer);
|
|
|
|
if (item && item.mux) {
|
|
logger.debug(`Temporarily saved '${target}', queued for muxing`);
|
|
} else {
|
|
logger.verbose(`Saved '${target}'`);
|
|
}
|
|
|
|
return target;
|
|
}
|
|
|
|
async function save(requestedFilepath, bufferOrBuffers, item) {
|
|
const pathElements = getPathElements(requestedFilepath);
|
|
const buffers = [].concat(bufferOrBuffers); // allow for single stream argument
|
|
|
|
await fs.ensureDir(pathElements.dir);
|
|
|
|
return Promise.all(buffers.map((buffer, index) => {
|
|
const target = path.join(pathElements.root, pathElements.dir, `${pathElements.name}${buffers.length > 1 ? `-${index}` : ''}${pathElements.ext}`);
|
|
|
|
return writeBufferToFile(target, buffer, item);
|
|
}));
|
|
}
|
|
|
|
module.exports = save;
|