目前我有一个文本文件,如下所示:
function NAME(){ }我想在NAME之后在括号中插入一个字符串,我已经研究了几个小时,但却找不到足够好的解释这个问题。 任何肝脏将很高兴。 作为额外的信息,我在api中这样做,所以我也使用nodejs。
我知道如何读取文件,但我不知道如何在正确的位置写入字符串。 如果需要,我也可以覆盖该文件。
谢谢。
编辑:名称将通过我拥有的不同文件进行更改,但格式不会,因此唯一需要做的是在第一个“()”内向此文件添加一个字符串。
编辑2:
var dir = 'operations/'; fs.readFile(dir+req.params.oid+".js", 'utf8', function (err,data) { if (err) { return console.log(err); } var res = data.split('('); var newStr = res[0] + '(' + req.body.name + res[1]; fs.writeFile(dir+req.params.oid+".js", newStr, function(err) { if (err){ throw 'error writing file: ' + err; } else{ console.log("File saved"); } }); });req.body.name是我需要添加到括号中的字符串。
At the moment I have a text file looking like this:
function NAME(){ }I would like to insert a string in the parenthesis after NAME, I have been researching for hours and have not been able to find a good enough explanation for this problem. Any hep will be gladly appreciated. As extra information I am doing this inside an api so I am using nodejs as well.
I know how to read the file but I am not sure how to then write the string in the correct place. I can overwrite the file if needed as well.
Thanks.
Edit: The Name will change through the different files I have, however the format will not, thus the only thing that would need to be done is add a string to this file inside the first "()".
Edit 2:
var dir = 'operations/'; fs.readFile(dir+req.params.oid+".js", 'utf8', function (err,data) { if (err) { return console.log(err); } var res = data.split('('); var newStr = res[0] + '(' + req.body.name + res[1]; fs.writeFile(dir+req.params.oid+".js", newStr, function(err) { if (err){ throw 'error writing file: ' + err; } else{ console.log("File saved"); } }); });req.body.name is the string I need added into the parenthesis.
最满意答案
对于String部分,类似这样的工作:
var param = 'myParam'; var str = 'function NAME(){ }'; var res = str.split('('); var newStr = res[0] + '(' + param + res[1]; // newStr == 'function NAME(myParam){ }'对于nodejs,尝试查看'fs'模块来读取文件并编写它( https://nodejs.org/api/fs.html )
For the String part, something like this work :
var param = 'myParam'; var str = 'function NAME(){ }'; var res = str.split('('); var newStr = res[0] + '(' + param + res[1]; // newStr == 'function NAME(myParam){ }'For nodejs, try to look at the 'fs' module to read file and write it (https://nodejs.org/api/fs.html)
更多推荐
发布评论