feat: add util function convert csv to data

This commit is contained in:
Methapon Metanipat 2024-11-11 09:17:16 +07:00
parent 84a6e57b77
commit 5888f3a9dd
3 changed files with 29 additions and 0 deletions

View file

@ -31,6 +31,7 @@
"socket.io-client": "^4.7.5",
"tesseract.js": "^5.1.1",
"thai-baht-text": "^2.0.5",
"udsv": "^0.6.0",
"uuid": "^10.0.0",
"vue": "^3.4.38",
"vue-i18n": "^9.14.0",

8
pnpm-lock.yaml generated
View file

@ -56,6 +56,9 @@ importers:
thai-baht-text:
specifier: ^2.0.5
version: 2.0.5
udsv:
specifier: ^0.6.0
version: 0.6.0
uuid:
specifier: ^10.0.0
version: 10.0.0
@ -3395,6 +3398,9 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
udsv@0.6.0:
resolution: {integrity: sha512-na+0EoqqpDeNKZ0HVTtgYtFP9aQgsMwPM77UEK7g4OX2C42w+Qw7QZs9t1ocDGLidtcKJnsPy+o5XrBYaZfzCA==}
ufo@1.5.3:
resolution: {integrity: sha512-Y7HYmWaFwPUmkoQCUIAYpKqkOf+SbVj/2fJJZ4RJMCfZp0rTGwRbzQD+HghfnhKOjL9E01okqz+ncJskGYfBNw==}
@ -7345,6 +7351,8 @@ snapshots:
typescript@5.5.4: {}
udsv@0.6.0: {}
ufo@1.5.3: {}
undici-types@6.19.8: {}

View file

@ -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;
}