簡體   English   中英

在剝離Jekyll前題的同時將Markdown文件轉換為PDF

[英]Convert Markdown files to PDF while stripping Jekyll Front-Matter

我有一個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/;

其中說“-”之間的所有內容或換行符

使它不貪心

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM