使用node.js将文本文件中的正则表达式替换为文件内容 [英] Replace regular expression in text file with file contents using node.js

查看:366
本文介绍了使用node.js将文本文件中的正则表达式替换为文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题适用于任何文本文件,但由于我想将其用于HTML替换,我将使用HTML文件作为示例。我已经看过像gulp注入和替换npm这样的东西,但是没有找到我需要的东西。

This question would apply to any text file but as I want to use it for HTML replacements I will use HTML files for examples. I have looked at things like gulp inject and replace on npm but neither seamed to do quite what i needed.

我想有一些引用另一个文件的占位符文本。当通过此替换功能运行时,占位符文本将被文件内容替换。

I would like to have some placeholder text that references another file. when run through this replacement function the placeholdler text is replaced by the contents of the file.

main.html

main.html

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

other.js

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

转换后输出文件应为。

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

我有以下内容但不知道如何使它在节点中使用文件流。

I have got to the following but don't know how to make it work with file streams in 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()

If your files are reasonable in size, you can avoid using streams and go with a custom replacer for 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');

这篇关于使用node.js将文本文件中的正则表达式替换为文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆