0
# File Classes
1
2
Three specialized file classes for representing different types of file storage and enabling seamless file operations.
3
4
## Capabilities
5
6
### FileRef Class
7
8
Represents a file stored remotely with a content digest, typically in cloud storage.
9
10
```typescript { .api }
11
/**
12
* File stored remotely with content digest
13
*/
14
class FileRef implements File {
15
public type: 'FileRef';
16
public mode: number;
17
public digest: string;
18
public contentType: string | undefined;
19
20
constructor(options: FileRefOptions);
21
toStream(): NodeJS.ReadableStream;
22
toStreamAsync(): Promise<NodeJS.ReadableStream>;
23
}
24
25
interface FileRefOptions {
26
/** File mode/permissions (default: 0o100644) */
27
mode?: number;
28
/** Content digest in format "sha:hash" or "sha+ephemeral:hash" */
29
digest: string;
30
/** MIME content type */
31
contentType?: string;
32
/** Whether file contents can change (affects caching) */
33
mutable?: boolean;
34
}
35
```
36
37
**Usage Examples:**
38
39
```typescript
40
import { FileRef } from "@now/build-utils";
41
42
// Create reference to cached file
43
const cachedFile = new FileRef({
44
digest: "sha:a1b2c3d4e5f6789...",
45
contentType: "application/javascript",
46
mode: 0o100644
47
});
48
49
// Create reference to ephemeral file
50
const tempFile = new FileRef({
51
digest: "sha+ephemeral:x9y8z7w6v5u4321...",
52
contentType: "text/plain",
53
mutable: true
54
});
55
56
// Stream file contents
57
const stream = cachedFile.toStream();
58
stream.pipe(process.stdout);
59
60
// Async streaming
61
const asyncStream = await cachedFile.toStreamAsync();
62
```
63
64
### FileFsRef Class
65
66
Represents a file in the local filesystem with direct access to the file path.
67
68
```typescript { .api }
69
/**
70
* File in the local filesystem
71
*/
72
class FileFsRef implements File {
73
public type: 'FileFsRef';
74
public mode: number;
75
public fsPath: string;
76
public contentType: string | undefined;
77
78
constructor(options: FileFsRefOptions);
79
static fromFsPath(options: FileFsRefOptions): Promise<FileFsRef>;
80
static fromStream(options: FromStreamOptions): Promise<FileFsRef>;
81
toStream(): NodeJS.ReadableStream;
82
toStreamAsync(): Promise<NodeJS.ReadableStream>;
83
}
84
85
interface FileFsRefOptions {
86
/** File mode/permissions (default: 0o100644) */
87
mode?: number;
88
/** MIME content type */
89
contentType?: string;
90
/** Absolute path to file in filesystem */
91
fsPath: string;
92
}
93
94
interface FromStreamOptions {
95
/** File mode/permissions (default: 0o100644) */
96
mode?: number;
97
/** MIME content type */
98
contentType?: string;
99
/** Input stream to read from */
100
stream: NodeJS.ReadableStream;
101
/** Destination path to write stream to */
102
fsPath: string;
103
}
104
```
105
106
**Usage Examples:**
107
108
```typescript
109
import { FileFsRef } from "@now/build-utils";
110
111
// Create from existing file
112
const existingFile = new FileFsRef({
113
fsPath: "/path/to/file.js",
114
contentType: "application/javascript"
115
});
116
117
// Create from file path with automatic mode detection
118
const autoModeFile = await FileFsRef.fromFsPath({
119
fsPath: "/path/to/script.py",
120
contentType: "text/x-python"
121
});
122
123
// Create from stream (downloads and saves)
124
const streamFile = await FileFsRef.fromStream({
125
stream: someReadableStream,
126
fsPath: "/tmp/downloaded-file.txt",
127
mode: 0o100644
128
});
129
130
// Stream file contents
131
const stream = existingFile.toStream();
132
```
133
134
### FileBlob Class
135
136
Represents a file stored in memory as a string or Buffer.
137
138
```typescript { .api }
139
/**
140
* File stored in memory as string or Buffer
141
*/
142
class FileBlob implements File {
143
public type: 'FileBlob';
144
public mode: number;
145
public data: string | Buffer;
146
public contentType: string | undefined;
147
148
constructor(options: FileBlobOptions);
149
static fromStream(options: FromStreamOptions): Promise<FileBlob>;
150
toStream(): NodeJS.ReadableStream;
151
}
152
153
interface FileBlobOptions {
154
/** File mode/permissions (default: 0o100644) */
155
mode?: number;
156
/** MIME content type */
157
contentType?: string;
158
/** File content as string or Buffer */
159
data: string | Buffer;
160
}
161
162
interface FromStreamOptions {
163
/** File mode/permissions (default: 0o100644) */
164
mode?: number;
165
/** MIME content type */
166
contentType?: string;
167
/** Input stream to read into memory */
168
stream: NodeJS.ReadableStream;
169
}
170
```
171
172
**Usage Examples:**
173
174
```typescript
175
import { FileBlob } from "@now/build-utils";
176
177
// Create from string
178
const textFile = new FileBlob({
179
data: "console.log('Hello, World!');",
180
contentType: "application/javascript",
181
mode: 0o100644
182
});
183
184
// Create from Buffer
185
const binaryFile = new FileBlob({
186
data: Buffer.from([0x89, 0x50, 0x4E, 0x47]), // PNG header
187
contentType: "image/png"
188
});
189
190
// Create from stream (loads into memory)
191
const streamBlob = await FileBlob.fromStream({
192
stream: someReadableStream,
193
contentType: "text/plain"
194
});
195
196
// Stream file contents
197
const stream = textFile.toStream();
198
stream.pipe(process.stdout); // Outputs: console.log('Hello, World!');
199
200
// Access data directly
201
console.log(textFile.data); // "console.log('Hello, World!');"
202
```
203
204
## Base File Interface
205
206
All file classes implement the common File interface:
207
208
```typescript { .api }
209
interface File {
210
/** File type identifier */
211
type: string;
212
/** File mode/permissions */
213
mode: number;
214
/** MIME content type */
215
contentType?: string;
216
/** Convert file to readable stream */
217
toStream(): NodeJS.ReadableStream;
218
/** Absolute filesystem path (FileFsRef only) */
219
fsPath?: string;
220
}
221
222
interface Files {
223
[filePath: string]: File;
224
}
225
```
226
227
## File Usage Patterns
228
229
### Build Pipeline Integration
230
231
```typescript
232
import { FileFsRef, FileBlob, download } from "@now/build-utils";
233
234
// Typical build pipeline
235
const sourceFiles = {
236
"src/index.ts": new FileFsRef({ fsPath: "/project/src/index.ts" }),
237
"package.json": new FileFsRef({ fsPath: "/project/package.json" })
238
};
239
240
// Download files to build directory
241
const workFiles = await download(sourceFiles, "/tmp/build");
242
243
// Generate additional files during build
244
const outputFiles = {
245
...workFiles,
246
"dist/index.js": new FileBlob({
247
data: "// Compiled JavaScript code...",
248
contentType: "application/javascript"
249
}),
250
"build-info.json": new FileBlob({
251
data: JSON.stringify({
252
timestamp: Date.now(),
253
version: "1.0.0"
254
}),
255
contentType: "application/json"
256
})
257
};
258
259
// Create Lambda from mixed file types
260
const lambda = await createLambda({
261
files: outputFiles,
262
handler: "dist/index.handler",
263
runtime: "nodejs14.x"
264
});
265
```
266
267
### File Type Selection Guide
268
269
**Use FileRef when:**
270
- Files are stored in remote cache/CDN
271
- Working with cached build artifacts
272
- Files have content-based hashing
273
- Need automatic caching behavior
274
275
**Use FileFsRef when:**
276
- Files exist on local filesystem
277
- Need direct file system access
278
- Working with source code files
279
- Preserving file metadata is important
280
281
**Use FileBlob when:**
282
- Files are generated in memory
283
- Small configuration files
284
- Template-generated content
285
- Dynamic content creation
286
287
## File Operations
288
289
### Stream Handling
290
291
All file classes provide consistent streaming interfaces:
292
293
```typescript
294
// Consistent streaming across file types
295
async function processFile(file: File) {
296
const stream = file.toStream();
297
298
// Pipe to destination
299
stream.pipe(destinationStream);
300
301
// Or collect data
302
const chunks: Buffer[] = [];
303
stream.on('data', chunk => chunks.push(chunk));
304
stream.on('end', () => {
305
const content = Buffer.concat(chunks);
306
console.log('File size:', content.length);
307
});
308
}
309
```
310
311
### File Transformation
312
313
```typescript
314
// Transform files between types
315
import { FileFsRef, FileBlob } from "@now/build-utils";
316
317
// FileFsRef -> FileBlob (load into memory)
318
const fsFile = new FileFsRef({ fsPath: "/path/to/file.txt" });
319
const blobFile = await FileBlob.fromStream({
320
stream: fsFile.toStream(),
321
contentType: fsFile.contentType
322
});
323
324
// FileBlob -> FileFsRef (save to disk)
325
const memoryFile = new FileBlob({ data: "Hello World" });
326
const diskFile = await FileFsRef.fromStream({
327
stream: memoryFile.toStream(),
328
fsPath: "/tmp/output.txt"
329
});
330
```
331
332
## Performance Considerations
333
334
- **FileRef**: Network latency for remote files, but good caching
335
- **FileFsRef**: Fast local access, but limited by disk I/O
336
- **FileBlob**: Fastest access, but limited by memory usage
337
338
Choose the appropriate file type based on your performance and storage requirements.