【问题标题】:Convert Markdown files to PDF while stripping Jekyll Front-Matter在剥离 Jekyll Front-Matter 时将 Markdown 文件转换为 PDF
【发布时间】:2016-04-10 06:45:54
【问题描述】:

我有一个 javascript 文件,它应该遍历给定的目录、索引文件、从它们中剥离出前面的内容,然后将它们转换为 PDF 文件。

我的大部分过程都在工作,但由于某种原因,我的 .replace 函数似乎没有做任何事情。

代码如下:

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 );

    } );
  } );
} );

【问题讨论】:

    标签: javascript node.js pdf jekyll


    【解决方案1】:

    在正则表达式模式中, . char 匹配除换行符以外的所有内容。

    FrontMatter 有换行符,因此您必须将其添加到模式中。

    点赞:var pattern = /^---(.|\n)*?---\n/;

    在 --- “标签”之间表示一切或换行

    那个?让它不贪心

    【讨论】:

    • 非常感谢!我很高兴知道这只是模式。
    猜你喜欢
    • 2014-10-23
    • 1970-01-01
    • 2014-03-14
    • 2015-12-24
    • 2018-06-25
    • 2015-08-17
    • 2019-01-27
    • 2015-05-12
    • 1970-01-01
    相关资源
    最近更新 更多