hillary clinton
hillary clinton

Reputation: 11

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. e.g;

Joe
Alex
Patricia
Emma

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

Upvotes: 0

Views: 1839

Answers (2)

adeneo
adeneo

Reputation: 318192

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.

Upvotes: 2

Benjamin Charais
Benjamin Charais

Reputation: 1368

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.

Upvotes: 0

Related Questions