我用readFile方法读取了一个文本文档,并得到了当前的字符串。 我需要修改里面的一些特定字段并保存文件并保持原始格式
在读取文件中我得到以下“字符串”
\r\nAPP_HOST=mo-d6fa.corp\r\nAPP_PORT=5000\r\nINS_PORT=50100\r\nPORT=66000\r\n
我只需要更改属性的编号
- 端口=4000
- APP_PORT =4000
我使用fs.readFile(filePath, 'utf8')
,响应是这个文件
最佳答案
您可以将其修改为对象,设置值,然后使用 Array.prototype.reduce
返回字符串:
var rawValues = "\r\nAPP_HOST=mo-d6fa.corp\r\nAPP_PORT=5000\r\nINS_PORT=50100\r\nPORT=66000\r\n";
// #1 You need to turn raw string into an array using String.prototype.split
// #2 It's time to reduce the array into an object to be able to access
// config values as a key-value pair store
var values = rawValues.trim().split("\r\n").reduce(
function(result, next, index, sourceArray) {
var keyValuePair = sourceArray[index].split("=");
result[keyValuePair[0]] = keyValuePair[1];
return result;
}, {});
// Now you can alter config values like a dictionary:
values["PORT"] = "9995";
values["APP_PORT"] = "9999";
// or using dot syntax if possible settings have valid JavaScript
// variable names...
values.PORT = "9995";
values.APP_PORT = "9999";
// ...more settings...
// #3 Once you've edited your settings, it's time to reduce each property
// as part of a new raw string containing all configurations.
rawValues = Object.keys(values).reduce(function(previousValue, property, index) {
previousValue += property + "=" + values[property] + "\r\n";
return previousValue;
}, "");
// Now PORT and APP_PORT contain their new values...
document.getElementById("rawResult").textContent = JSON.stringify(rawValues);
<div id="rawResult"></div>
建议
恕我直言,如果您可以将配置转换为有效的 JSON,生活会更容易。
例如,您的原始配置可以是{ "APP_HOST": "mo-d6fa.corp", "APP_PORT": 5000, "INS_PORT": 50100, "PORT": 66000 }
。看看这如何简化您的问题:
var rawConfig = '{ "APP_HOST": "mo-d6fa.corp", "APP_PORT": 5000, "INS_PORT": 50100, "PORT": 66000 }';
var config = JSON.parse(rawConfig);
config["APP_PORT"] = 6000;
config["PORT"] = 7000;
rawConfig = JSON.stringify(config);
document.getElementById("result").textContent = rawConfig;
<div id="result"></div>
您无需使用自己的配置解析器,只需使用 JSON,这是一种众所周知的模式,它有一个内置的、开箱即用的解析器,作为地球上每个 Web 浏览器 NodeJS 的一部分甚至非 JavaScript 平台,如 .NET、Java...
关于javascript - 修改特定文本的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32064648/