Home > Enterprise >  I can't concatenate 2 strings with Nodejs and javascript
I can't concatenate 2 strings with Nodejs and javascript

Time:10-01

I'm having a very strange problem. I want to pull data from txt file and add page parameter to the end. But it doesn't adding to the end, it adds to the beginning. Can you help me ?

Where is error in my code ?

Codes:

let fs = require("fs");
let text = fs.readFileSync("./categories.txt");
let links = await text.toString().split("\n")

for (var i = 0; i < links.length; i  ) {
    for (var p = 1; p <= page; p  ) {
        let pageUrl = links[i]   '?page=' p
        console.log(pageUrl)
    }
}

Result:

Text

CodePudding user response:

Explanation

The string contains both \r and \n characters as Windows has CRLF line endings. splitting Hello\r\nWorld\r\n on \n will give: [ 'Hello\r', 'World\r', '' ] Displaying \r without \n will have the effect of returning the output cursor to the beginning of the line without advancing the cursor to the line below. The next text that gets written will overwrite the characters in the output.

e.g. logging the string ABCDEFGHIJKLMNOPQRSTUVWXYZ\r?page=1 twice will look like this:

?page=1HIJKLMNOPQRSTUVWXYZ
?page=1HIJKLMNOPQRSTUVWXYZ

That's because it writes the whole alphabet, then the \r goes to the beginning of the line and the remaining ?page=1 overwrites the ABCDEFG part of the output.

I suggest using console.log(JSON.stringify(pageUrl)) to help you diagnose such problems in the future. And be aware of platform-specific line endings.

Solution

Once you know what's happening (as I have explained above), your problem is best solved by node.js: read a text file into an array. (Each line an item in the array.)

text.toString().replace(/\r\n/g,'\n').split('\n') is one of the approaches listed there.

  • Related