1
0
mirror of synced 2025-12-22 11:26:57 -05:00
Files
docs/lib/read-frontmatter.js
Jason Etcovitch 0ec47e0246 Only read the frontmatter from files in warm-server (#17222)
* Add read-frontmatter.js

* Use it

* Page static read/init are async now

* Fix some blockers

* I'm confused

* Fix some more bugs

* Use frontmatter schema, ensure end fence exists

* Fix a bug

* Still read full contents for index.md files

* Remove comment

* Only get ToC items for index pages

* Readd frontmatter error and verdadero handling

* Fix some borked tests

* Simplify the code

* Add a comment

* Remove redundant variable

* Re-simplify the Page construction

* End chunk _after_ endline

* Just use Page.init
2021-01-14 10:46:59 -05:00

48 lines
1.5 KiB
JavaScript

const fs = require('fs')
const fm = require('./frontmatter')
const endLine = '\n---\n'
/**
* Reads the given filepath, but only up until `endLine`, using streams to
* read each chunk and close the stream early.
*/
async function readFrontmatter (filepath) {
const readStream = fs.createReadStream(filepath, { encoding: 'utf8', emitClose: true })
return new Promise((resolve, reject) => {
let frontmatter = ''
readStream
.on('data', function (chunk) {
const endOfFrontmatterIndex = chunk.indexOf(endLine)
if (endOfFrontmatterIndex !== -1) {
frontmatter += chunk.slice(0, endOfFrontmatterIndex + endLine.length)
// Stop early!
readStream.destroy()
} else {
frontmatter += chunk
}
})
.on('error', (error) => reject(error))
// Stream has been destroyed and file has been closed
.on('close', () => resolve(frontmatter))
})
}
/**
* Read only the frontmatter from a file
*/
module.exports = async function fmfromf (filepath, languageCode) {
let fileContent = filepath.endsWith('index.md')
// For index files, we need to read the whole file because they contain ToC info
? await fs.promises.readFile(filepath, 'utf8')
// For everything else, only read the frontmatter
: await readFrontmatter(filepath)
// TODO remove this when crowdin-support issue 66 has been resolved
if (languageCode !== 'en' && fileContent.includes(': verdadero')) {
fileContent = fileContent.replace(': verdadero', ': true')
}
return fm(fileContent, { filepath })
}