0

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

2
  • 1
    await text.toString().split("\n") - awaiting a synchronous method makes no sense at all. Commented Sep 30, 2022 at 13:57
  • 2
    The "Result" is not possible with the "Code" you've shown -> Add an actual minimal reproducible example (and show us the actual content (at least a minimal amount) of categories.txt) Commented Sep 30, 2022 at 14:00

1 Answer 1

1

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.

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

1 Comment

Thank you so much for your so long description you are my hero :)

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.