Thought this wouldn't be this difficult, but I'm simply trying to get the contents of a file and store each line into an array.
The 'file.txt' file (formatted as plain text):
file1.dwg
file2.dwg
file3.pdf
file4.dwg
file5.pdf
My javascript code:
function readTextFile('file.txt') {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", 'file.txt', false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
The syntax errors shown in the console:
- safari: SyntaxError: Unexpected string literal 'file.txt'. Expected a parameter pattern or a ')' in parameter list.
- chrome: Uncaught SyntaxError: Unexpected string
I'm running the files on a simple live server, with the following file structure:
- file.txt
- page.html
- script.js
The page.html just calls the script and is somewhere where I can work and open the console.
Why are the errors occurring, and how can they be fixed? I've tried to follow the instructions from this other post, but it has also failed: How to read a local text file?
Then I also tried the node solution and made my code like this:
var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
console.log(array[i]);
}
I know nothing about Node but gave it a go - the errors were:
- chrome: Uncaught ReferenceError: require is not defined
- safari: ReferenceError: Can't find variable: require
Thanks for any help here - I don't know how to fix this seemingly simple problem.