UNPKG

pdfmake

Version:

Client/server side PDF printing in pure JavaScript

82 lines (77 loc) • 2.46 kB
"use strict"; exports.__esModule = true; exports.default = exports.VirtualFileSystem = void 0; const normalizeFilename = filename => { if (filename.indexOf(__dirname) === 0) { filename = filename.substring(__dirname.length); } if (filename.indexOf('/') === 0) { filename = filename.substring(1); } return filename; }; class VirtualFileSystem { constructor(parent = null) { this.storage = {}; this.parent = parent; } /** * @param {string} filename * @returns {boolean} */ existsSync(filename) { if (typeof filename !== 'string') { return false; } if (this.parent && this.parent.existsSync(filename)) { return true; } const normalizedFilename = normalizeFilename(filename); return typeof this.storage[normalizedFilename] !== 'undefined'; } /** * @param {string} filename * @param {?string|?object} options * @returns {string|Buffer} */ readFileSync(filename, options) { if (this.parent && this.parent.existsSync(filename)) { return this.parent.readFileSync(filename, options); } const normalizedFilename = normalizeFilename(filename); const encoding = typeof options === 'object' ? options.encoding : options; if (!this.existsSync(normalizedFilename)) { throw new Error(`File '${normalizedFilename}' not found in virtual file system`); } const buffer = this.storage[normalizedFilename]; if (encoding) { return buffer.toString(encoding); } return buffer; } /** * @param {string} filename * @param {string|Buffer} content * @param {?string|?object} options */ writeFileSync(filename, content, options) { const normalizedFilename = normalizeFilename(filename); const encoding = typeof options === 'object' ? options.encoding : options; if (!content && !options) { throw new Error('No content'); } this.storage[normalizedFilename] = encoding || typeof content === 'string' ? Buffer.from(content, encoding) : content; } /** * @param {string} filename */ unlinkSync(filename) { const normalizedFilename = normalizeFilename(filename); if (typeof this.storage[normalizedFilename] === 'undefined') { throw new Error(`File '${normalizedFilename}' not found in virtual file system`); } delete this.storage[normalizedFilename]; } } exports.VirtualFileSystem = VirtualFileSystem; var _default = exports.default = new VirtualFileSystem();