这个问题适用于任何文本文件,但由于我想将它用于 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/