javascript - 将 Markdown 文件转换为 PDF,同时剥离 Jekyll Front-Matter

标签 javascript node.js pdf jekyll

我有一个 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 );

    } );
  } );
} );

最佳答案

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

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

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

这表示 ---“标签”之间的所有内容或换行符

那个?使其不贪婪

关于javascript - 将 Markdown 文件转换为 PDF,同时剥离 Jekyll Front-Matter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36526772/

相关文章:

javascript - 如何在后续保存时重新启动 Gulp 任务?

javascript - 修改 FullCalendar Javascript 插件布局

javascript - Mongoose "this.model is not a function"

php - 使用 WordPress 插件从 pdf 创建 jpg

javascript - Kendo UI 组合框打破 knockout 绑定(bind)

javascript - jQuery模态窗口的加载效果是怎么实现的呢?

javascript - node.js Web 服务器作为独立应用程序

node.js - 通过 Node js 测试 Backbone 模型

excel - VBA 运行时错误 : save PowerPoint Presentation as PDF

c# - iTextSharp : table row gets pushed to new page if it doesn't fit on the current one