I am trying to load a file using the input tag in html with type 'file'
<input type="file">
And then with this file, I am trying to split each line and return the resulting array into an array called lines
.
I have tried moving the console.log(lines) around but I only get the correct result when the console.log is inside the .onload function.
var input = document.querySelector('input[type="file"]')
input.addEventListener('change', function (e) {
let lines = new Array();
console.log(input.files)
const reader = new FileReader()
reader.onload = function () {
lines = reader.result.split('\n');
}
reader.readAsText(input.files[0]);
console.log(lines)
})
How can i ensure that the lines
array has had the correct split lines put into it so that I can then use the lines
array in other parts of my overall function
just try push split value in array. it may work for you.
var input = document.querySelector('input[type="file"]')
let lines = [];
input.addEventListener('change', function (e) {
const reader = new FileReader()
reader.onload = function () {
lines.push(reader.result.split('\n'));
}
reader.readAsText(input.files[0]);
console.log(lines);
})
<input type="file">