简体   繁体   中英

Add string in a specific part of text file Javascript

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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM