在文本文件Javascript的特定部分添加字符串(Add string in a specific part of text file Javascript)

编程入门 行业动态 更新时间:2024-10-28 14:35:04
在文本文件Javascript的特定部分添加字符串(Add string in a specific part of text file Javascript)

目前我有一个文本文件,如下所示:

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)

更多推荐

本文发布于:2023-07-23 00:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1225261.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   文本文件   Add   string   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!