我正在使用Node JS和库替换文件
我正在使用一些函数到文件(functions.js)
并将另一个文件用于调用函数(index.js)
当我第一次启动脚本时,它可以工作,但是随后我重新启动了脚本,并且'] ['不能替换为','
Function.js
var priority = "";
var expectedValue = "";
var score1 = "";
var score2 = "";
/* some function*/
function generateJSON(key){
var table = []
table.push({"executionDate":date,
"issueID":key,
"priority":{
"jira": priority,
"computed":score1
},
"expectedValue":{
"jira": expected,
"computed":score2
}
})
var json = JSON.stringify(table,null, 2);
fs.appendFile('templateLog1.json', json, 'utf8', function (err) {
if (err) console.error(err)
});
}
function replaceCaracter(){
const options = {
files: 'templateLog1.json',
from: '][',
to: ',',
};
replace(options, (error, results) => {
if (error) {
return console.error('Error occurred:', error);
}
console.log('Replacement results:', results);
});
}
Index.js
setTimeout(function() {
functions.getAllIssueForSCII().then(function(json){
for (let i=0; i<json.issues.length;i++){
functions.generateJSON(json.issues[i].key);
functions.replaceCaracter()
}
});
}, 1000)
实际结果:
[
{
"executionDate": 1556197884153,
"issueID": "SCII-10",
"priority": {
"jira": "Lowest",
"computed": -25
},
"expectedValue": {
"jira": "Low",
"computed": -10
}
}
,
{
"executionDate": 1556197884153,
"issueID": "SCII-7",
"priority": {
"jira": "Low",
"computed": -10
},
"expectedValue": {
"jira": "Low",
"computed": -10
}
}
][
{
"executionDate": 1556197896877,
"issueID": "SCII-10",
"priority": {
"jira": "Lowest",
"computed": -25
},
"expectedValue": {
"jira": "Low",
"computed": -10
}
}
][
{
"executionDate": 1556197896877,
"issueID": "SCII-7",
"priority": {
"jira": "Low",
"computed": -10
},
"expectedValue": {
"jira": "Low",
"computed": -10
}
}
]
预期结果:
[
{
"executionDate": 1556197884153,
"issueID": "SCII-10",
"priority": {
"jira": "Lowest",
"computed": -25
},
"expectedValue": {
"jira": "Low",
"computed": -10
}
}
,
{
"executionDate": 1556197884153,
"issueID": "SCII-7",
"priority": {
"jira": "Low",
"computed": -10
},
"expectedValue": {
"jira": "Low",
"computed": -10
}
}
,
{
"executionDate": 1556197896877,
"issueID": "SCII-10",
"priority": {
"jira": "Lowest",
"computed": -25
},
"expectedValue": {
"jira": "Low",
"computed": -10
}
}
,
{
"executionDate": 1556197896877,
"issueID": "SCII-7",
"priority": {
"jira": "Low",
"computed": -10
},
"expectedValue": {
"jira": "Low",
"computed": -10
}
}
]
答案 0 :(得分:0)
这是一个常见错误。如您所见,][
的第一次出现确实已被替换。
当您使用带有简单字符串的String.replace()
方法作为第一个参数(要替换的字符串)时,通常会发生这种情况。
您需要做的是使用带有global
标志的正则表达式。尝试将']['
对象中的/]\[/g
更改为options
。
有关String.replace
方法的更多详细信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace