From 77a2d9ce8058663f10ba15ad7d1b18682a58d1e8 Mon Sep 17 00:00:00 2001 From: MapleCCC Date: Thu, 21 Oct 2021 18:33:09 +0800 Subject: [PATCH] Fix the bug that line endings are poorly handled on Windows platform, which causes insidious bug like #161 --- doctoc.js | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/doctoc.js b/doctoc.js index 578dfa93..31bc67c1 100755 --- a/doctoc.js +++ b/doctoc.js @@ -2,7 +2,8 @@ 'use strict'; -var path = require('path') +var os = require('os') + , path = require('path') , fs = require('fs') , minimist = require('minimist') , file = require('./lib/file') @@ -16,6 +17,28 @@ function cleanPath(path) { return homeExpanded.replace(/\s/g, '\\ '); } +function readFile(path, encoding) { + var content = fs.readFileSync(path, encoding); + + // On Windows platform, convert CRLF line endings to LF line endings. + // The line ending style is unified for easier handling. + if (os.EOL === '\r\n') { + content = content.replace(/\r\n/g, '\n'); + } + + return content; +} + +function writeFile(path, data, encoding) { + + // On Windows platform, convert LF line endings to CRLF line endings. + if (os.EOL === '\r\n') { + data = data.replace(/(?