-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathfile-stream.ts
More file actions
229 lines (206 loc) · 6.09 KB
/
file-stream.ts
File metadata and controls
229 lines (206 loc) · 6.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import { Readable } from "stream";
import { ReadableStream } from "stream/web";
import {
createReadStream, createWriteStream, promises as fs, Stats,
} from "fs";
import { tmpdir } from "os";
import {
join, basename,
} from "path";
import { pipeline } from "stream/promises";
import { v4 as uuidv4 } from "uuid";
import * as mime from "mime-types";
export interface FileMetadata {
size: number;
contentType?: string;
lastModified?: Date;
name?: string;
etag?: string;
}
/**
* @param pathOrUrl - a file path or a URL
* @returns a Readable stream of the file content
*/
export async function getFileStream(pathOrUrl: string): Promise<Readable> {
if (isDataUrl(pathOrUrl)) {
return getDataUrlStream(pathOrUrl);
} else if (isUrl(pathOrUrl)) {
const response = await fetch(pathOrUrl);
if (!response.ok || !response.body) {
throw new Error(`Failed to fetch ${pathOrUrl}: ${response.status} ${response.statusText}`);
}
return Readable.fromWeb(response.body as ReadableStream<Uint8Array>);
} else {
await safeStat(pathOrUrl);
return createReadStream(pathOrUrl);
}
}
/**
* @param pathOrUrl - a file path or a URL
* @returns a Readable stream of the file content and its metadata
*/
export async function getFileStreamAndMetadata(pathOrUrl: string): Promise<{ stream: Readable; metadata: FileMetadata }> {
if (isDataUrl(pathOrUrl)) {
return getDataUrlStreamAndMetadata(pathOrUrl);
} else if (isUrl(pathOrUrl)) {
return await getRemoteFileStreamAndMetadata(pathOrUrl);
} else {
return await getLocalFileStreamAndMetadata(pathOrUrl);
}
}
function isUrl(pathOrUrl: string): boolean {
try {
new URL(pathOrUrl);
return true;
} catch {
return false;
}
}
function isDataUrl(pathOrUrl: string): boolean {
return pathOrUrl.startsWith("data:");
}
interface ParsedDataUrl {
mediaType: string;
isBase64: boolean;
data: string;
}
function parseDataUrl(dataUrl: string): ParsedDataUrl {
// Format: data:[<mediatype>][;base64],<data>
const match = dataUrl.match(/^data:([^;,]*)?(?:;(base64))?,(.*)$/);
if (!match) {
throw new Error("Invalid data URL format");
}
const [
,
mediaType = "text/plain;charset=US-ASCII",
base64Flag,
data,
] = match;
return {
mediaType,
isBase64: base64Flag === "base64",
data,
};
}
function getDataUrlStream(dataUrl: string): Readable {
const parsed = parseDataUrl(dataUrl);
const buffer = parsed.isBase64
? Buffer.from(parsed.data, "base64")
: Buffer.from(decodeURIComponent(parsed.data), "utf-8");
return Readable.from(buffer);
}
function getDataUrlStreamAndMetadata(dataUrl: string): { stream: Readable; metadata: FileMetadata } {
const parsed = parseDataUrl(dataUrl);
const buffer = parsed.isBase64
? Buffer.from(parsed.data, "base64")
: Buffer.from(decodeURIComponent(parsed.data), "utf-8");
const ext = mime.extension(parsed.mediaType);
const name = ext
? `file.${ext}`
: "file";
const metadata: FileMetadata = {
size: buffer.length,
contentType: parsed.mediaType || undefined,
name,
};
return {
stream: Readable.from(buffer),
metadata,
};
}
async function safeStat(path: string): Promise<Stats> {
try {
return await fs.stat(path);
} catch {
throw new Error(`File not found: ${path}`);
}
}
async function getLocalFileStreamAndMetadata(
filePath: string,
): Promise<{ stream: Readable; metadata: FileMetadata }> {
const stats = await safeStat(filePath);
const contentType = mime.lookup(filePath) || undefined;
const metadata: FileMetadata = {
size: stats.size,
lastModified: stats.mtime,
name: basename(filePath),
contentType,
};
const stream = createReadStream(filePath);
return {
stream,
metadata,
};
}
async function getRemoteFileStreamAndMetadata(url: string): Promise<{ stream: Readable; metadata: FileMetadata }> {
const response = await fetch(url);
if (!response.ok || !response.body) {
throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
}
const headers = response.headers;
const contentLength = headers.get("content-length");
const lastModified = headers.get("last-modified")
? new Date(headers.get("last-modified")!)
: undefined;
const etag = headers.get("etag") || undefined;
const urlObj = new URL(url);
const name = basename(urlObj.pathname);
const contentType = headers.get("content-type") || mime.lookup(urlObj.pathname) || undefined;
const baseMetadata = {
contentType,
lastModified,
name,
etag,
};
// If we have content-length, we can stream directly
if (contentLength) {
const metadata: FileMetadata = {
...baseMetadata,
size: parseInt(contentLength, 10),
};
const stream = Readable.fromWeb(response.body as ReadableStream<Uint8Array>);
return {
stream,
metadata,
};
}
// No content-length header - need to download to temporary file to get size
return await downloadToTemporaryFile(response, baseMetadata);
}
async function downloadToTemporaryFile(response: Response, baseMetadata: Partial<FileMetadata>): Promise<{ stream: Readable; metadata: FileMetadata }> {
// Generate unique temporary file path
const tempFileName = `file-stream-${uuidv4()}`;
const tempFilePath = join(tmpdir(), tempFileName);
// Download to temporary file
const fileStream = createWriteStream(tempFilePath);
const webStream = Readable.fromWeb(response.body as ReadableStream<Uint8Array>);
try {
await pipeline(webStream, fileStream);
const stats = await fs.stat(tempFilePath);
const metadata: FileMetadata = {
...baseMetadata,
size: stats.size,
};
const stream = createReadStream(tempFilePath);
const cleanup = async () => {
try {
await fs.unlink(tempFilePath);
} catch {
// Ignore cleanup errors
}
};
stream.once("close", cleanup);
stream.once("end", cleanup);
stream.once("error", cleanup);
return {
stream,
metadata,
};
} catch (err) {
// Cleanup on error
try { await fs.unlink(tempFilePath); } catch {
// Ignore cleanup errors
}
throw err;
}
}