使用md5 grunt任务生成md5文件名。现在我想用任务回调中的新文件名重命名HTML文件中的源。我想知道最简单的方法是什么。


当前回答

如果有人想使用基于承诺的'fs'模块的任务。

const fs = require('fs').promises;

// Below statements must be wrapped inside the 'async' function:
const data = await fs.readFile(someFile, 'utf8');
const result = data.replace(/string to be replaced/g, 'replacement');
await fs.writeFile(someFile, result,'utf8');

其他回答

因为replace对我不起作用,我创建了一个简单的npm包replace-in-file来快速替换一个或多个文件中的文本。这部分是基于@asgoth的回答。

编辑(2016年10月3日):包现在支持承诺和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);
}

<p>请点击下面的{{link}}验证账号</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' })

当然,您可以改进读取模板函数,将其作为流读取,并按行组合字节,使其更有效

如果有人想使用基于承诺的'fs'模块的任务。

const fs = require('fs').promises;

// Below statements must be wrapped inside the 'async' function:
const data = await fs.readFile(someFile, 'utf8');
const result = data.replace(/string to be replaced/g, 'replacement');
await fs.writeFile(someFile, result,'utf8');

我在用一串大代码替换一个小占位符时遇到了问题。

我正在做:

var replaced = original.replace('PLACEHOLDER', largeStringVar);

我发现问题出在JavaScript的特殊替换模式上,如下所述。由于我使用的代码作为替换字符串有一些$,它是混乱的输出。

我的解决方案是使用函数替换选项,它不做任何特殊替换:

var replaced = original.replace('PLACEHOLDER', function() {
    return largeStringVar;
});

通常,我使用tiny-replace-files替换文件中的文本。这个pkg更小更轻… https://github.com/Rabbitzzc/tiny-replace-files

import { replaceStringInFilesSync } from 'tiny-replace-files'

const options = {
  files: 'src/targets/index.js',
  from: 'test-plugin',
  to: 'self-name',
}

# await
const result = replaceStringInFilesSync(options)
console.info(result)