0

I am trying to concatenate strings in Node.js . I started with a very basic example, I am trying to read a file, and simply concatenate all the lines one by one to a new object, but from some reason when I do console.log, only the last line appears. Its like each new line runs over the other.

here is the code

fs.readFile("C:/example.srt", function(error, data) {
    if (error) { throw error; }else {
        var newData = "";
        data.toString().split("\n").forEach(function (line) {
            newData = newData + line;
        });

        console.log(newData);
    }
});
3
  • try fs.readFile('path_to_file', 'utf8', callback()) Commented Oct 29, 2015 at 14:00
  • Can you log data.toString().split("\n").length at line 4? Commented Oct 29, 2015 at 14:07
  • The example is working on my side , testing on a dummy text file Commented Oct 29, 2015 at 14:09

1 Answer 1

2

You must be running on a windows platform where the line separator is \r\n so when you split by \n the carriage return is still present which overwrites the newData string. Simply change to ...().split('\r\n')

Sign up to request clarification or add additional context in comments.

1 Comment

WOW you won't belive the amount of time I spent on this. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.