0
# File Operations
1
2
Temporary file creation and management with full control over file descriptors, permissions, and cleanup behavior.
3
4
## Capabilities
5
6
### Asynchronous File Creation
7
8
Creates and opens a temporary file asynchronously.
9
10
```javascript { .api }
11
/**
12
* Creates and opens a temporary file
13
* @param {Options|Function} options - Configuration options or callback function
14
* @param {Function} callback - Callback function (err, path, fd, cleanupCallback) => void
15
*/
16
function file(options, callback);
17
```
18
19
**Callback Parameters:**
20
- `err` (Error|null): Error object or null if successful
21
- `path` (string): Full path to the created temporary file
22
- `fd` (number): File descriptor for the opened file (-1 if discarded)
23
- `cleanupCallback` (Function): Function to manually remove the file
24
25
**Usage Examples:**
26
27
```javascript
28
const tmp = require("tmp");
29
30
// Basic file creation
31
tmp.file(function(err, path, fd, cleanupCallback) {
32
if (err) throw err;
33
34
console.log("File:", path);
35
console.log("File descriptor:", fd);
36
37
// Write to the file using the file descriptor
38
const fs = require("fs");
39
fs.writeSync(fd, "Hello, temporary file!");
40
41
// Clean up when done
42
cleanupCallback();
43
});
44
45
// File creation with options
46
tmp.file({
47
mode: 0o644,
48
prefix: "myapp-",
49
postfix: ".txt"
50
}, function(err, path, fd, cleanupCallback) {
51
if (err) throw err;
52
53
console.log("Custom temp file:", path);
54
// File will have name like: /tmp/myapp-12345-67890.txt
55
56
cleanupCallback();
57
});
58
59
// Discard file descriptor for stream usage
60
tmp.file({ discardDescriptor: true }, function(err, path, fd, cleanupCallback) {
61
if (err) throw err;
62
63
console.log("File path:", path);
64
console.log("File descriptor:", fd); // undefined
65
66
// Now safe to use with fs.createWriteStream without holding extra descriptor
67
const fs = require("fs");
68
const stream = fs.createWriteStream(path);
69
stream.write("Stream data");
70
stream.end();
71
72
cleanupCallback();
73
});
74
```
75
76
### Synchronous File Creation
77
78
Creates and opens a temporary file synchronously.
79
80
```javascript { .api }
81
/**
82
* Creates and opens a temporary file synchronously
83
* @param {Options} options - Configuration options
84
* @returns {FileSyncObject} Object with name, fd, and removeCallback
85
* @throws {Error} If file creation fails
86
*/
87
function fileSync(options);
88
```
89
90
**Return Value:**
91
```javascript { .api }
92
interface FileSyncObject {
93
name: string; // Full path to the temporary file
94
fd: number; // File descriptor (-1 if discarded)
95
removeCallback: Function; // Cleanup function
96
}
97
```
98
99
**Usage Examples:**
100
101
```javascript
102
const tmp = require("tmp");
103
104
// Basic synchronous file creation
105
const tmpFile = tmp.fileSync();
106
console.log("Temp file:", tmpFile.name);
107
console.log("File descriptor:", tmpFile.fd);
108
109
// Write to the file
110
const fs = require("fs");
111
fs.writeSync(tmpFile.fd, "Synchronous data");
112
113
// Clean up
114
tmpFile.removeCallback();
115
116
// File creation with custom options
117
const customFile = tmp.fileSync({
118
mode: 0o600,
119
prefix: "secure-",
120
postfix: ".tmp",
121
dir: "cache" // Create in cache subdirectory of temp dir
122
});
123
124
console.log("Custom file:", customFile.name);
125
customFile.removeCallback();
126
127
// Discard descriptor for external management
128
const streamFile = tmp.fileSync({ discardDescriptor: true });
129
console.log("Stream file:", streamFile.name);
130
console.log("File descriptor:", streamFile.fd); // undefined
131
132
// Use with streams
133
const writeStream = fs.createWriteStream(streamFile.name);
134
writeStream.write("Stream content");
135
writeStream.end();
136
137
streamFile.removeCallback();
138
```
139
140
### File Descriptor Control
141
142
The tmp library provides fine-grained control over file descriptor lifecycle:
143
144
#### Discard Descriptor
145
146
Use `discardDescriptor: true` when you want tmp to close the file descriptor immediately after creation. This is useful when using the file with streams or other APIs that open their own descriptors.
147
148
```javascript
149
tmp.file({ discardDescriptor: true }, function(err, path, fd, cleanupCallback) {
150
// fd will be undefined
151
// Safe to use path with fs.createReadStream, fs.createWriteStream, etc.
152
});
153
```
154
155
#### Detach Descriptor
156
157
Use `detachDescriptor: true` when you want to manage the file descriptor yourself. The cleanup callback will not attempt to close the descriptor.
158
159
```javascript
160
tmp.file({ detachDescriptor: true }, function(err, path, fd, cleanupCallback) {
161
// You are responsible for closing fd
162
// cleanupCallback() will only remove the file, not close the descriptor
163
164
// Later, when you're done with the descriptor:
165
fs.closeSync(fd);
166
cleanupCallback();
167
});
168
```
169
170
### File Options
171
172
All file operations support the following options:
173
174
```javascript { .api }
175
interface FileOptions {
176
mode?: number; // File permissions (default: 0o600)
177
prefix?: string; // Filename prefix (default: "tmp")
178
postfix?: string; // Filename postfix
179
template?: string; // Template with XXXXXX (e.g., "temp-XXXXXX.txt")
180
name?: string; // Fixed filename (relative to dir/tmpdir)
181
dir?: string; // Subdirectory within tmpdir
182
tmpdir?: string; // Override system temp directory
183
tries?: number; // Max naming attempts (default: 3)
184
keep?: boolean; // Skip automatic cleanup
185
detachDescriptor?: boolean; // Don't close descriptor in cleanup
186
discardDescriptor?: boolean; // Close descriptor immediately after creation
187
}
188
```
189
190
**Important Notes:**
191
192
- File permissions default to `0o600` (owner read/write only) for security
193
- The `template` option must contain exactly one `XXXXXX` pattern which gets replaced with random characters
194
- When `name` is specified, `tries` is automatically set to 1
195
- The `keep` option prevents automatic cleanup but manual cleanup via callback still works
196
- Only one of `detachDescriptor` or `discardDescriptor` should be used