-2

We need to extract information from a .txt file, into a .js file. We've tried using 'Fetch API' but without luck, is there any other way to go about this.

We are using a Node.js Server to see what's going on

This is the contents of the .txt file

2min = 2:00
2min away = 2:00
ScoreAway = 7
ScoreHome = 8
Time = 30:00
halvleg = 2nd
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
Noddy
  • 3
  • 1
  • 2
    You can read the file with [`fs`](https://nodejs.org/api/fs.html) – Thomas Sablik Jan 13 '21 at 20:37
  • 3
    In the browser, you're pretty limited. If you're doing this within Node (server), then you have access to an entire filesystem API to read files from disk. – oooyaya Jan 13 '21 at 20:37
  • 1
    Welcome to SO! I recommend all new users visit [ask] for tips on writing well-formed questions. It is unclear where the file lives, and where you need to read it and send it; if this is a Node server, the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) makes little sense. Where does the file live? Is your goal simply to read a `.txt` from the filesystem and manipulate its contents into a node server on the same filesystem? If so, @ThomasSablik is correct- [`fs`](https://nodejs.org/api/fs.html) is what you'll want. If not, please clarify your question. Good luck! – Alexander Nied Jan 13 '21 at 20:41
  • Short: Serverside use fs and clientside use XMLHttpRequest. – Maik Lowrey Jan 13 '21 at 20:48
  • "We've tried using 'Fetch API' but without luck" — What did you try? What was the result? Were there error messages? Do you know how to see the error messages in your environment? You said you were using "a Node.js Server to see what's going on", what does that mean? Were you running your JS in node? Were you making HTTP requests to a server written in Node.js from a browser? – Quentin Jan 13 '21 at 20:51

1 Answers1

-1

Serverside use Node Js and Clientside use fs. In a browser you can use XMLHttpRequest. Like this:

function readTxtFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", "neuro.txt", false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                let allText = rawFile.responseText;
                console.log(allText);
            }
        }
    }
    rawFile.send(null);
}
readTxtFile();
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79