0
# Name Generation
1
2
Generate unique temporary filenames without creating actual filesystem objects, useful for custom file creation workflows and when you need control over the file creation process.
3
4
## Capabilities
5
6
### Asynchronous Name Generation
7
8
Generates a unique temporary filename asynchronously without creating the file.
9
10
```javascript { .api }
11
/**
12
* Generates a unique temporary filename
13
* @param {Options|Function} options - Configuration options or callback function
14
* @param {Function} callback - Callback function (err, name) => void
15
*/
16
function tmpName(options, callback);
17
```
18
19
**Callback Parameters:**
20
- `err` (Error|null): Error object or null if successful
21
- `name` (string): Generated unique temporary filename path
22
23
**Usage Examples:**
24
25
```javascript
26
const tmp = require("tmp");
27
28
// Basic name generation
29
tmp.tmpName(function(err, path) {
30
if (err) throw err;
31
32
console.log("Generated temp filename:", path);
33
// Example: /tmp/tmp-12345-67890abcdef
34
35
// Now you can create the file yourself with custom logic
36
const fs = require("fs");
37
const fd = fs.openSync(path, "w", 0o600);
38
fs.writeSync(fd, "Custom file creation");
39
fs.closeSync(fd);
40
41
// Clean up manually
42
fs.unlinkSync(path);
43
});
44
45
// Name generation with custom options
46
tmp.tmpName({
47
prefix: "myapp-",
48
postfix: ".json",
49
dir: "data"
50
}, function(err, path) {
51
if (err) throw err;
52
53
console.log("Custom temp filename:", path);
54
// Example: /tmp/data/myapp-12345-67890abcdef.json
55
56
// Create JSON file with specific formatting
57
const fs = require("fs");
58
const data = { id: Date.now(), type: "temporary" };
59
fs.writeFileSync(path, JSON.stringify(data, null, 2));
60
61
// Process the file...
62
63
fs.unlinkSync(path);
64
});
65
66
// Template-based name generation
67
tmp.tmpName({ template: "cache-XXXXXX.tmp" }, function(err, path) {
68
if (err) throw err;
69
70
console.log("Template filename:", path);
71
// Example: /tmp/cache-abc123.tmp
72
73
// Create cache file with atomic write
74
const fs = require("fs");
75
const tempPath = path + ".writing";
76
fs.writeFileSync(tempPath, "cache data");
77
fs.renameSync(tempPath, path); // Atomic operation
78
79
fs.unlinkSync(path);
80
});
81
```
82
83
### Synchronous Name Generation
84
85
Generates a unique temporary filename synchronously.
86
87
```javascript { .api }
88
/**
89
* Generates a unique temporary filename synchronously
90
* @param {Options} options - Configuration options
91
* @returns {string} Generated unique temporary filename path
92
* @throws {Error} If name generation fails after max tries
93
*/
94
function tmpNameSync(options);
95
```
96
97
**Usage Examples:**
98
99
```javascript
100
const tmp = require("tmp");
101
const fs = require("fs");
102
103
// Basic synchronous name generation
104
const tempName = tmp.tmpNameSync();
105
console.log("Generated temp filename:", tempName);
106
107
// Create and use the file
108
fs.writeFileSync(tempName, "Synchronous content");
109
console.log("File content:", fs.readFileSync(tempName, "utf8"));
110
fs.unlinkSync(tempName);
111
112
// Name generation with specific requirements
113
const configName = tmp.tmpNameSync({
114
prefix: "config-",
115
postfix: ".yaml",
116
mode: 0o644,
117
dir: "configs"
118
});
119
120
console.log("Config filename:", configName);
121
122
// Create configuration file
123
const config = `
124
app:
125
name: MyApp
126
debug: true
127
`;
128
fs.writeFileSync(configName, config.trim());
129
130
// Use the config file...
131
132
fs.unlinkSync(configName);
133
134
// Generate multiple unique names
135
const names = [];
136
for (let i = 0; i < 5; i++) {
137
names.push(tmp.tmpNameSync({ prefix: `batch-${i}-` }));
138
}
139
140
console.log("Generated batch names:", names);
141
142
// Create all files
143
names.forEach((name, index) => {
144
fs.writeFileSync(name, `Batch file ${index}`);
145
});
146
147
// Clean up
148
names.forEach(name => fs.unlinkSync(name));
149
```
150
151
### Advanced Name Generation Patterns
152
153
#### Custom Directory Structure
154
155
```javascript
156
const tmp = require("tmp");
157
const fs = require("fs");
158
const path = require("path");
159
160
// Generate name in nested directory structure
161
tmp.tmpName({
162
dir: "project/build/artifacts",
163
prefix: "artifact-",
164
postfix: ".tar.gz"
165
}, function(err, artifactPath) {
166
if (err) throw err;
167
168
// Ensure parent directories exist
169
fs.mkdirSync(path.dirname(artifactPath), { recursive: true });
170
171
// Create artifact file
172
fs.writeFileSync(artifactPath, "artifact data");
173
174
console.log("Artifact created:", artifactPath);
175
176
// Clean up
177
fs.unlinkSync(artifactPath);
178
});
179
```
180
181
#### Template Patterns for Specific Use Cases
182
183
```javascript
184
// Log file with timestamp pattern
185
const logName = tmp.tmpNameSync({
186
template: "app-log-XXXXXX.log",
187
dir: "logs"
188
});
189
190
// Database backup pattern
191
const backupName = tmp.tmpNameSync({
192
template: "db-backup-XXXXXX.sql",
193
tmpdir: "/var/backups"
194
});
195
196
// Session file pattern
197
const sessionName = tmp.tmpNameSync({
198
template: "session-XXXXXX.json",
199
dir: "sessions",
200
mode: 0o600 // Secure permissions
201
});
202
```
203
204
#### Retry Logic and Error Handling
205
206
```javascript
207
const tmp = require("tmp");
208
209
// Handle name generation with custom retry logic
210
function generateNameWithRetry(options, maxAttempts = 5) {
211
return new Promise((resolve, reject) => {
212
let attempts = 0;
213
214
function tryGenerate() {
215
attempts++;
216
tmp.tmpName(options, function(err, name) {
217
if (err) {
218
if (attempts < maxAttempts) {
219
console.log(`Attempt ${attempts} failed, retrying...`);
220
setTimeout(tryGenerate, 100); // Wait before retry
221
} else {
222
reject(new Error(`Failed to generate name after ${maxAttempts} attempts`));
223
}
224
} else {
225
resolve(name);
226
}
227
});
228
}
229
230
tryGenerate();
231
});
232
}
233
234
// Usage
235
generateNameWithRetry({ prefix: "critical-", postfix: ".data" })
236
.then(name => {
237
console.log("Generated with retry:", name);
238
// Use the name...
239
})
240
.catch(err => {
241
console.error("Name generation failed:", err.message);
242
});
243
```
244
245
### Name Generation Options
246
247
Name generation supports all the standard options:
248
249
```javascript { .api }
250
interface NameGenerationOptions {
251
prefix?: string; // Filename prefix (default: "tmp")
252
postfix?: string; // Filename postfix
253
template?: string; // Template with XXXXXX (e.g., "temp-XXXXXX.txt")
254
name?: string; // Fixed filename (relative to dir/tmpdir)
255
dir?: string; // Subdirectory within tmpdir
256
tmpdir?: string; // Override system temp directory
257
tries?: number; // Max naming attempts (default: 3)
258
}
259
```
260
261
**Important Notes:**
262
263
- Name generation only creates the filename - you must create the actual file yourself
264
- The generated path is guaranteed to not exist at the time of generation, but this can change before you create the file
265
- Use atomic file operations (write to temp name, then rename) for thread-safe file creation
266
- Template patterns must contain exactly one `XXXXXX` sequence
267
- The `tries` option controls how many attempts are made if the generated name already exists
268
- Name generation is faster than file/directory creation since no filesystem operations are performed
269
- Generated names use the same crypto-based randomness as file and directory creation for security