使用md5 grunt任务生成md5文件名。现在我想用任务回调中的新文件名重命名HTML文件中的源。我想知道最简单的方法是什么。
当前回答
在Linux或Mac上,keep很简单,只需使用sed和shell。不需要外部库。下面的代码可以在Linux上运行。
const shell = require('child_process').execSync
shell(`sed -i "s!oldString!newString!g" ./yourFile.js`)
Mac上的sed语法有点不同。我现在不能测试它,但我相信你只需要在“-i”后面添加一个空字符串:
const shell = require('child_process').execSync
shell(`sed -i "" "s!oldString!newString!g" ./yourFile.js`)
最后一个“!”后面的“g”使sed替换一行上的所有实例。删除它,将只替换每行中第一个出现的内容。
其他回答
因为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);
}
通常,我使用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)
也许“replace”模块(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,
});
ES2017/8 for Node 7.6+,带有用于原子替换的临时写文件。
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`)
Mac上的sed语法有点不同。我现在不能测试它,但我相信你只需要在“-i”后面添加一个空字符串:
const shell = require('child_process').execSync
shell(`sed -i "" "s!oldString!newString!g" ./yourFile.js`)
最后一个“!”后面的“g”使sed替换一行上的所有实例。删除它,将只替换每行中第一个出现的内容。
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 在Ubuntu上安装Node.js
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置