| 1 |
"use strict"; |
| 2 |
|
| 3 |
const { ParserError } = require("../util/errors"); |
| 4 |
|
| 5 |
let TEXT_REGEXP = /\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)$/i; |
| 6 |
|
| 7 |
module.exports = { |
| 8 |
/** |
| 9 |
* The order that this parser will run, in relation to other parsers. |
| 10 |
* |
| 11 |
* @type {number} |
| 12 |
*/ |
| 13 |
order: 300, |
| 14 |
|
| 15 |
/** |
| 16 |
* Whether to allow "empty" files (zero bytes). |
| 17 |
* |
| 18 |
* @type {boolean} |
| 19 |
*/ |
| 20 |
allowEmpty: true, |
| 21 |
|
| 22 |
/** |
| 23 |
* The encoding that the text is expected to be in. |
| 24 |
* |
| 25 |
* @type {string} |
| 26 |
*/ |
| 27 |
encoding: "utf8", |
| 28 |
|
| 29 |
/** |
| 30 |
* Determines whether this parser can parse a given file reference. |
| 31 |
* Parsers that return true will be tried, in order, until one successfully parses the file. |
| 32 |
* Parsers that return false will be skipped, UNLESS all parsers returned false, in which case |
| 33 |
* every parser will be tried. |
| 34 |
* |
| 35 |
* @param {object} file - An object containing information about the referenced file |
| 36 |
* @param {string} file.url - The full URL of the referenced file |
| 37 |
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) |
| 38 |
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver |
| 39 |
* @returns {boolean} |
| 40 |
*/ |
| 41 |
canParse (file) { |
| 42 |
// Use this parser if the file is a string or Buffer, and has a known text-based extension |
| 43 |
return (typeof file.data === "string" || Buffer.isBuffer(file.data)) && TEXT_REGEXP.test(file.url); |
| 44 |
}, |
| 45 |
|
| 46 |
/** |
| 47 |
* Parses the given file as text |
| 48 |
* |
| 49 |
* @param {object} file - An object containing information about the referenced file |
| 50 |
* @param {string} file.url - The full URL of the referenced file |
| 51 |
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) |
| 52 |
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver |
| 53 |
* @returns {string} |
| 54 |
*/ |
| 55 |
parse (file) { |
| 56 |
if (typeof file.data === "string") { |
| 57 |
return file.data; |
| 58 |
} |
| 59 |
else if (Buffer.isBuffer(file.data)) { |
| 60 |
return file.data.toString(this.encoding); |
| 61 |
} |
| 62 |
else { |
| 63 |
throw new ParserError("data is not text", file.url); |
| 64 |
} |
| 65 |
} |
| 66 |
}; |