feat: add util function convert csv to data
This commit is contained in:
parent
84a6e57b77
commit
5888f3a9dd
3 changed files with 29 additions and 0 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import { inferSchema, initParser } from 'udsv';
|
||||
export function fileToBase64(file: File) {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
|
|
@ -6,3 +7,22 @@ export function fileToBase64(file: File) {
|
|||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
export async function csvToData<T extends Record<string, any>>(
|
||||
file: File,
|
||||
): Promise<T[] | null> {
|
||||
const stream = file.stream().pipeThrough(new TextDecoderStream());
|
||||
const reader = stream.getReader();
|
||||
|
||||
const { value, done } = await reader.read();
|
||||
|
||||
if (value) {
|
||||
const parser = initParser(inferSchema(value));
|
||||
const data = parser.typedObjs<T>(value);
|
||||
return data;
|
||||
}
|
||||
|
||||
if (done) return null;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue