javascript - 使用 node.js 将文本文件中的正则表达式替换为文件内容

标签 javascript regex node.js build

这个问题适用于任何文本文件,但由于我想将它用于 HTML 替换,因此我将使用 HTML 文件作为示例。我看过 npm 上的 gulp inject 和 replace 之类的东西,但两者都不能完全满足我的需要。

我想要一些引用另一个文件的占位符文本。通过此替换函数运行时,占位符文本将替换为文件的内容。

main.html

<script><replace src="./other.js" /></script>

其他.js

console.log("Hello, world!");

转换后的输出文件应该是。

<script>console.log("Hello, world!")</script>

我已经了解了以下内容,但不知道如何让它与 Node 中的文件流一起工作。

var REGEX = /<replace src="(.+)" \/>/;

function replace(file){
  match = file.match(REGEX);
  var placeholder = match[0];
  if (placeholder) {
    return file.replace(placeholder, match[1].toUpperCase());
    // toUpperCase is just an example and instead should lookup a file for contents
  }
}

最佳答案

如果您的文件大小合理,您可以避免使用流并使用 string.replace() 的自定义替换器:

var fs = require('fs');

function replace(path) {
    var REGEX = /<replace src="(.+)" \/>/g;
    // load the html file
    var fileContent = fs.readFileSync(path, 'utf8');

    // replacePath is your match[1]
    fileContent = fileContent.replace(REGEX, function replacer(match, replacePath) {
        // load and return the replacement file
        return fs.readFileSync(replacePath, 'utf8');
    });

    // this will overwrite the original html file, change the path for test
    fs.writeFileSync(path, fileContent);
}

replace('./main.html');

使用流

var es = require('event-stream');

function replaceWithStreams(path) {
    var REGEX = /<replace src="(.+)" \/>/g;
    fs.createReadStream(path, 'utf8')
        .pipe(es.split()) // split the input file into lines
        .pipe(es.map(function (line, next) {
            line = line.replace(REGEX, function replacer(match, replacePath) {
                // better to keep a readFileSync here for clarity
                return fs.readFileSync(replacePath, 'utf8'); 
            });
            next(null, line);
        })).pipe(fs.createWriteStream(path)); // change path if needed
}

replaceWithStreams('./main.html');

关于javascript - 使用 node.js 将文本文件中的正则表达式替换为文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34498059/

相关文章:

javascript - Web加密 : Safari cannot exportKey() and promise seems to never resolve/fail

javascript - 在 forEach 循环 javascript 中创建对象时出现问题

mysql - sequelize.js addIndex 不使用 indexName

javascript - 无法从 Node JS 中的另一个箭头函数调用箭头函数

javascript - Firebase 数据库以编程方式检查下载的数据大小

javascript - 使用 php 和 mysql 定期检测数据库中的变化

JavaScript 正则表达式 : match all quotes in given HTML attribute

regex - 不甘心回头看

Python - 使用正则表达式更新 2 个节点之间的 xml 值 - re.sub 不起作用

node.js - Windows > Vagrant > nodejs 看不到本地包