How to Use JavaScript to Read Local Text File and Read Line by Line

How to use Javascript to read local text file and read line by line?

Without jQuery:

const $output = document.getElementById('output')
document.getElementById('file').onchange = function() {
var file = this.files[0];

var reader = new FileReader();
reader.onload = function(progressEvent) {
// Entire file
const text = this.result;
$output.innerText = text

// By lines
var lines = text.split('\n');
for (var line = 0; line < lines.length; line++) {
console.log(lines[line]);
}
};
reader.readAsText(file);
};
<input type="file" name="file" id="file">
<div id='output'>
...
</div>

How to read a local text file in the browser?

You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver)

function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}

And specify file:// in your filename:

readTextFile("file:///C:/your/path/to/file.txt");

How to read online file line by line?

You can use the Fetch API and read the response as text and iterate line by line

(async () => {
const response = await fetch("https://xn--qucu-hr5aza.cc/files/M%E1%BB%99t%20h%E1%BB%87%20th%E1%BB%91ng%20ni%E1%BB%81m%20tin/Node%20list");
const data = await response.text();
const lines = data.split("\n");
console.log(lines)
})();

Read a file one line at a time in node.js?

Since Node.js v0.12 and as of Node.js v4.0.0, there is a stable readline core module. Here's the easiest way to read lines from a file, without any external modules:

const fs = require('fs');
const readline = require('readline');

async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');

const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.

for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
}

processLineByLine();

Or alternatively:

var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('file.in')
});

lineReader.on('line', function (line) {
console.log('Line from file:', line);
});

The last line is read correctly (as of Node v0.12 or later), even if there is no final \n.

UPDATE: this example has been added to Node's API official documentation.

Read text file line by line and execute a function?

You can use the ReadLine module to read files line by line. You can append a list of the test results and then do something with them when the file is completely read:

const readline = require('readline');
const fs = require('fs');
const inputFileName = './testfile.txt';

const readInterface = readline.createInterface({
input: fs.createReadStream(inputFileName),
});

let testResults = [];
readInterface.on('line', line => {
testResult = test(line);
console.log(`Test result (line #${testResults.length+1}): `, testResult);
testResults.push({ input: line, testResult } );
});

// You can do whatever with the test results here.
readInterface.on('close', () => {
console.log("Test results:", testResults);
});

function test(str){

let regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; // email regex

str = str.split(",");

// string should be of length 3 with str[1] number of length 7
if(str && str.length === 3 && Number(str[1]) && str[1] ) {

let temp = str[0].split("-");

// check for 85aecb80-ac00-40e3-813c-5ad62ee93f42 separately.
if(temp && temp.length === 5 && /[a-zA-Z\d]{8}/.test(temp[0]) && /[a-zA-Z\d]{4}/.test(temp[1]) && /[a-zA-Z\d]{4}/.test(temp[2]) && /[a-zA-Z\d]{4}/.test(temp[3]) && /[a-zA-Z\d]{12}/.test(temp[4])){

// email regex
if(regex.test(str[2])) {
return true;
} else {
return false;
}
} else {
return false
}
} else {
return false;
}
}


Related Topics



Leave a reply



Submit