Reputation: 596
I used this FileReader to read csvs:
readDocument(fileChangeEvent: Event) {
return new Observable<any>(obs => {
const file = (fileChangeEvent.target as HTMLInputElement).files[0];
if (file) {
const fileReader = new FileReader();
fileReader.onload = e => {
obs.next({
name: file.name,
result: fileReader.result
});
};
fileReader.readAsText(file);
}
});
With this, I could then use the file in my subscription and use it's name or value anytime:
this.readDocument(csv).subscribe(value => {
console.log(value.name);
console.log(value.result
}
Meanwhile I have this Filereader for reading a folder that has csvs stored inside:
public readFolder(files: string[]) {
this.fileCache = [];
this.readFile(0, files);
return this.folderReader$.asObservable();
}
private readFile(index, files) {
const reader = new FileReader();
if (index >= files.length) {
this.folderReader$.next(this.fileCache);
return;
}
const file = files[index];
const filename = file.name;
console.log(filename);
reader.onload = (e: any) => {
this.fileCache.push(e.target.result);
this.readFile(index + 1, files);
};
reader.readAsBinaryString(file);
}
Now, with this i do get an array which is filled with the data of each csv in the folder. I can then later use for example a loop to show the all the file-data.
files = []
this.folderReader.readFolder(csv.target.files).subscribe(files => {
files.forEach((value, key) => {
console.log(key + ': ' + value);
}
}
My problem is, id like to be able to read the value and the name of the file again, like in the first example. It should look something like this in the end:
this.folderReader.readFolder(csv.target.files).subscribe(files => {
files.forEach((file) => {
console.log(file.name)
console.log(file.result)
}
}
I am struggling to modify the second FileReader to give a similar output as the first just in an array. What can i do to improve my FileReader so it will give the output i want to? Is there an even easier way maybe?
Upvotes: 1
Views: 1107
Reputation: 12804
Try to use a simple model class to store file name and content (replaces your result):
class FileStorage {
name: string;
content: any;
contructor(name: string, content: any) {
this.name = name;
this.content = content;
}
}
Instead of pushing your content / result in the cache, you create a new object with filename and content:
private readFile(index, files) {
...
reader.onload = (e: any) => {
this.fileCache.push(new FileStorage(fileName, e.target.result));
...
Or you push just a plain object without typing (like in your filereader) ;-)
this.fileCache.push({
name: fileName,
content: e.target.result
});
Now you can get your data via:
files.forEach((file) => {
console.log(file.name)
console.log(file.content)
}
BTW: Have a look at node.js FileSystem Api, maybe a smarter way to deal with files.
E.g.: tutorialspoint Node FileSystem Examples
API Readfile fs.readfile.
Upvotes: 1