简体   繁体   中英

How can I add text to the end of each line of a File in node.js?

I have a file called Names.txt; inside this is a list of names of people, separated by a line. eg;

Joe
Alex
Patricia
Emma

How, in node.js, would I edit the file so there is an ":lastname" added to each line?

You'd get the file, split into lines, modify those lines, and write the file back again

fs.readFile('/path/to/Names.txt', function(err, result) {

    if (err) // handle errors

    var lines = result.split(/(\n|\r\n)/);

    var new_content = lines.map(function(line) {
        return line + ' lastname';
    }).join("\r\n")

    fs.writeFile('/path/to/Names.txt', new_content, 'utf8', function(err) {
        if (err) // handle errors
        console.log('The file has been saved!');
    });
});

That's the jist of it. Of course, you could keep a map of firstnames and lastnames, and insert the appropriate lastname, or do all sorts of other things, but you'd still have to go through the same process, fetch, split on newlines, modify, join together and save.

Building upon the previous answer, you would be looking to add the UTF8 encoding by implementing it as a parameter after the file path, it would look like this...

fs.readFile('/path/Names.txt', 'utf8', function(err, res) {
  if (err) throw err;

  var lines = res.split(/\n/);
  var new_content = lines.map(function(line) {
    return line + ' lastname';
  }).join('\n');

  fs.writeFile('/path/Names.txt', new_content, 'utf8', function(err) {
    if (err) throw err;
    console.log('The file has been saved!');
  });
});

this should fix your issue with the buffer looking return from the read command.

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