我使用md5 grunt任务生成MD5文件名。现在,我想使用任务回调中的新文件名重命名HTML文件中的源。我想知道什么是最简单的方法。
我使用md5 grunt任务生成MD5文件名。现在,我想使用任务回调中的新文件名重命名HTML文件中的源。我想知道什么是最简单的方法。
Answers:
您可以使用简单的正则表达式:
var result = fileAsString.replace(/string to be replaced/g, 'replacement');
所以...
var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/string to be replaced/g, 'replacement');
  fs.writeFile(someFile, result, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});
              由于replace对我不起作用,因此我创建了一个简单的npm包replace-in-file来快速替换一个或多个文件中的文本。它部分基于@asgoth的答案。
编辑(2016年10月3日):该软件包现在支持Promise和Glob,并且使用说明已更新以反映这一点。
编辑(2018年3月16日):该软件包现已累积每月超过10万次下载,并已扩展了其他功能和CLI工具。
安装:
npm install replace-in-file
需要模块
const replace = require('replace-in-file');
指定替换选项
const options = {
  //Single file
  files: 'path/to/file',
  //Multiple files
  files: [
    'path/to/file',
    'path/to/other/file',
  ],
  //Glob(s) 
  files: [
    'path/to/files/*.html',
    'another/**/*.path',
  ],
  //Replacement to make (string or regex) 
  from: /Find me/g,
  to: 'Replacement',
};
承诺的异步替换:
replace(options)
  .then(changedFiles => {
    console.log('Modified files:', changedFiles.join(', '));
  })
  .catch(error => {
    console.error('Error occurred:', error);
  });
回调的异步替换:
replace(options, (error, changedFiles) => {
  if (error) {
    return console.error('Error occurred:', error);
  }
  console.log('Modified files:', changedFiles.join(', '));
});
同步更换:
try {
  let changedFiles = replace.sync(options);
  console.log('Modified files:', changedFiles.join(', '));
}
catch (error) {
  console.error('Error occurred:', error);
}
              也许“替换”模块(www.npmjs.org/package/replace)也可以为您工作。它不需要您读取然后写入文件。
改编自文档:
// install:
npm install replace 
// require:
var replace = require("replace");
// use:
replace({
    regex: "string to be replaced",
    replacement: "replacement string",
    paths: ['path/to/your/file'],
    recursive: true,
    silent: true,
});
              readFile()与writeFile()接受的答案相同。
                    您还可以使用ShellJS中的“ sed”功能...
 $ npm install [-g] shelljs
 require('shelljs/global');
 sed('-i', 'search_pattern', 'replace_pattern', file);
访问ShellJs.org了解更多示例。
shxShellJs.org建议您使用npm脚本运行它。github.com/shelljs/shx
                    您可以在使用流读取文件的同时对其进行处理。就像使用缓冲区一样,但具有更方便的API。
var fs = require('fs');
function searchReplaceFile(regexpFind, replace, cssFileName) {
    var file = fs.createReadStream(cssFileName, 'utf8');
    var newCss = '';
    file.on('data', function (chunk) {
        newCss += chunk.toString().replace(regexpFind, replace);
    });
    file.on('end', function () {
        fs.writeFile(cssFileName, newCss, function(err) {
            if (err) {
                return console.log(err);
            } else {
                console.log('Updated!');
            }
    });
});
searchReplaceFile(/foo/g, 'bar', 'file.txt');
              bufferSize比您要替换的字符串长的字符串,并保存最后一个块并与当前块连接,您是否可以避免该问题。
                    适用于Node 7.6+的ES2017 / 8,带有用于原子替换的临时写入文件。
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))
async function replaceRegexInFile(file, search, replace){
  let contents = await fs.readFileAsync(file, 'utf8')
  let replaced_contents = contents.replace(search, replace)
  let tmpfile = `${file}.jstmpreplace`
  await fs.writeFileAsync(tmpfile, replaced_contents, 'utf8')
  await fs.renameAsync(tmpfile, file)
  return true
}
请注意,仅适用于较小的文件,因为它们将被读入内存。
在Linux或Mac上,keep很简单,只需将sed与shell配合使用即可。无需外部库。以下代码在Linux上有效。
const shell = require('child_process').execSync
shell(`sed -i "s!oldString!newString!g" ./yourFile.js`)
sed语法在Mac上略有不同。我现在无法对其进行测试,但是我相信您只需要在“ -i”之后添加一个空字符串:
const shell = require('child_process').execSync
shell(`sed -i "" "s!oldString!newString!g" ./yourFile.js`)
最后的“!”后面的“ g”!使sed替换一行上的所有实例。删除它,将仅替换每行的第一个匹配项。
扩展@Sanbor的答案,最有效的方法是将原始文件作为流读取,然后还将每个块流式传输到新文件中,然后最后用新文件替换原始文件。
async function findAndReplaceFile(regexFindPattern, replaceValue, originalFile) {
  const updatedFile = `${originalFile}.updated`;
  return new Promise((resolve, reject) => {
    const readStream = fs.createReadStream(originalFile, { encoding: 'utf8', autoClose: true });
    const writeStream = fs.createWriteStream(updatedFile, { encoding: 'utf8', autoClose: true });
    // For each chunk, do the find & replace, and write it to the new file stream
    readStream.on('data', (chunk) => {
      chunk = chunk.toString().replace(regexFindPattern, replaceValue);
      writeStream.write(chunk);
    });
    // Once we've finished reading the original file...
    readStream.on('end', () => {
      writeStream.end(); // emits 'finish' event, executes below statement
    });
    // Replace the original file with the updated file
    writeStream.on('finish', async () => {
      try {
        await _renameFile(originalFile, updatedFile);
        resolve();
      } catch (error) {
        reject(`Error: Error renaming ${originalFile} to ${updatedFile} => ${error.message}`);
      }
    });
    readStream.on('error', (error) => reject(`Error: Error reading ${originalFile} => ${error.message}`));
    writeStream.on('error', (error) => reject(`Error: Error writing to ${updatedFile} => ${error.message}`));
  });
}
async function _renameFile(oldPath, newPath) {
  return new Promise((resolve, reject) => {
    fs.rename(oldPath, newPath, (error) => {
      if (error) {
        reject(error);
      } else {
        resolve();
      }
    });
  });
}
// Testing it...
(async () => {
  try {
    await findAndReplaceFile(/"some regex"/g, "someReplaceValue", "someFilePath");
  } catch(error) {
    console.log(error);
  }
})()
              我会改用双工流。就像这里记录的nodejs文档双工流
转换流是双工流,其中输出是通过输入以某种方式计算的。
<p>Please click in the following {{link}} to verify the account</p>
function renderHTML(templatePath: string, object) {
    const template = fileSystem.readFileSync(path.join(Application.staticDirectory, templatePath + '.html'), 'utf8');
    return template.match(/\{{(.*?)\}}/ig).reduce((acc, binding) => {
        const property = binding.substring(2, binding.length - 2);
        return `${acc}${template.replace(/\{{(.*?)\}}/, object[property])}`;
    }, '');
}
renderHTML(templateName, { link: 'SomeLink' })
确保可以改进读取模板功能以流形式读取并逐行编写字节以使其更高效