[英]Convert Markdown files to PDF while stripping Jekyll Front-Matter
I have a javascript file that is supposed to loop through a given directory, index the files, strip the front-matter out of them, and then convert them into PDF files. 我有一个javascript文件,该文件应该在给定目录中循环,对文件进行索引,从文件中剔除最重要的内容,然后将其转换为PDF文件。
I have most of the process working, but for some reason my .replace
function doesn't seem to be doing anything. 我已经完成了大部分流程,但是由于某种原因,我的.replace
函数似乎没有执行任何操作。
Here's the code: 这是代码:
var fs = require( 'fs' );
var path = require( 'path' );
var process = require( 'process' );
var markdownpdf = require( 'markdown-pdf' )
var md_dir = "_pages";
var pdf_dir = "assets/pdf"
// Loop through all the files in the directory
fs.readdir( md_dir, function( err, files ) {
if( err ) {
console.error( "Could not list the directory.", err );
process.exit( 1 );
}
files.forEach( function( file, index ) {
// Make one pass and make the file complete
var md_path = path.join( md_dir, file );
var pdf_path = path.join( pdf_dir, file + '.pdf' );
fs.stat( md_path, function( error, stat ) {
if( error ) {
console.error( "Error stating file.", error );
return;
}
// Start PDF Process on the files
if( stat.isFile() ) {
console.log( "'%s' is a file.", md_path );
console.log( "Stripping Jekyll Front-Matter...");
var fileContents = fs.readFileSync(md_path, 'utf8');
var pattern = /^---\n.*\n---\n/;
// Strip everything between the first two sets of '---'
var stripped_md = fileContents.replace( pattern, '' );
console.log( "Front-Matter stripped." );
// Pass that to markdown-pdf
markdownpdf().from.string(stripped_md).to(pdf_path, function () {
console.log("Created", pdf_path)
} );
}
// If it's not a file
else if( stat.isDirectory() )
console.log( "'%s' is a directory.", md_path );
} );
} );
} );
In a regexp pattern the . 在正则表达式模式中。 char matches everything except a newline. char匹配除换行符以外的所有内容。
The FrontMatter has newlines so you have to add this to the pattern. FrontMatter有换行符,因此您必须将其添加到模式中。
Like: var pattern = /^---(.|\\n)*?---\\n/;
如: var pattern = /^---(.|\\n)*?---\\n/;
Which says everything or newline between the --- "tags" 其中说“-”之间的所有内容或换行符
The ? ? makes it non greedy 使它不贪心
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.