UNPKG

12 kBMarkdownView Raw
1# Tmp
2
3A simple temporary file and directory creator for [node.js.][1]
4
5[![Build Status](https://travis-ci.org/raszi/node-tmp.svg?branch=master)](https://travis-ci.org/raszi/node-tmp)
6[![Dependencies](https://david-dm.org/raszi/node-tmp.svg)](https://david-dm.org/raszi/node-tmp)
7[![npm version](https://badge.fury.io/js/tmp.svg)](https://badge.fury.io/js/tmp)
8[![API documented](https://img.shields.io/badge/API-documented-brightgreen.svg)](https://raszi.github.io/node-tmp/)
9[![Known Vulnerabilities](https://snyk.io/test/npm/tmp/badge.svg)](https://snyk.io/test/npm/tmp)
10
11## About
12
13This is a [widely used library][2] to create temporary files and directories
14in a [node.js][1] environment.
15
16Tmp offers both an asynchronous and a synchronous API. For all API calls, all
17the parameters are optional. There also exists a promisified version of the
18API, see [tmp-promise][5].
19
20Tmp uses crypto for determining random file names, or, when using templates,
21a six letter random identifier. And just in case that you do not have that much
22entropy left on your system, Tmp will fall back to pseudo random numbers.
23
24You can set whether you want to remove the temporary file on process exit or
25not.
26
27If you do not want to store your temporary directories and files in the
28standard OS temporary directory, then you are free to override that as well.
29
30## An Important Note on Compatibility
31
32See the [CHANGELOG](./CHANGELOG.md) for more information.
33
34### Version 0.1.0
35
36Since version 0.1.0, all support for node versions < 0.10.0 has been dropped.
37
38Most importantly, any support for earlier versions of node-tmp was also dropped.
39
40If you still require node versions < 0.10.0, then you must limit your node-tmp
41dependency to versions below 0.1.0.
42
43### Version 0.0.33
44
45Since version 0.0.33, all support for node versions < 0.8 has been dropped.
46
47If you still require node version 0.8, then you must limit your node-tmp
48dependency to version 0.0.33.
49
50For node versions < 0.8 you must limit your node-tmp dependency to
51versions < 0.0.33.
52
53## How to install
54
55```bash
56npm install tmp
57```
58
59## Usage
60
61Please also check [API docs][4].
62
63### Asynchronous file creation
64
65Simple temporary file creation, the file will be closed and unlinked on process exit.
66
67```javascript
68const tmp = require('tmp');
69
70tmp.file(function _tempFileCreated(err, path, fd, cleanupCallback) {
71 if (err) throw err;
72
73 console.log('File: ', path);
74 console.log('Filedescriptor: ', fd);
75
76 // If we don't need the file anymore we could manually call the cleanupCallback
77 // But that is not necessary if we didn't pass the keep option because the library
78 // will clean after itself.
79 cleanupCallback();
80});
81```
82
83### Synchronous file creation
84
85A synchronous version of the above.
86
87```javascript
88const tmp = require('tmp');
89
90const tmpobj = tmp.fileSync();
91console.log('File: ', tmpobj.name);
92console.log('Filedescriptor: ', tmpobj.fd);
93
94// If we don't need the file anymore we could manually call the removeCallback
95// But that is not necessary if we didn't pass the keep option because the library
96// will clean after itself.
97tmpobj.removeCallback();
98```
99
100Note that this might throw an exception if either the maximum limit of retries
101for creating a temporary name fails, or, in case that you do not have the permission
102to write to the directory where the temporary file should be created in.
103
104### Asynchronous directory creation
105
106Simple temporary directory creation, it will be removed on process exit.
107
108If the directory still contains items on process exit, then it won't be removed.
109
110```javascript
111const tmp = require('tmp');
112
113tmp.dir(function _tempDirCreated(err, path, cleanupCallback) {
114 if (err) throw err;
115
116 console.log('Dir: ', path);
117
118 // Manual cleanup
119 cleanupCallback();
120});
121```
122
123If you want to cleanup the directory even when there are entries in it, then
124you can pass the `unsafeCleanup` option when creating it.
125
126### Synchronous directory creation
127
128A synchronous version of the above.
129
130```javascript
131const tmp = require('tmp');
132
133const tmpobj = tmp.dirSync();
134console.log('Dir: ', tmpobj.name);
135// Manual cleanup
136tmpobj.removeCallback();
137```
138
139Note that this might throw an exception if either the maximum limit of retries
140for creating a temporary name fails, or, in case that you do not have the permission
141to write to the directory where the temporary directory should be created in.
142
143### Asynchronous filename generation
144
145It is possible with this library to generate a unique filename in the specified
146directory.
147
148```javascript
149const tmp = require('tmp');
150
151tmp.tmpName(function _tempNameGenerated(err, path) {
152 if (err) throw err;
153
154 console.log('Created temporary filename: ', path);
155});
156```
157
158### Synchronous filename generation
159
160A synchronous version of the above.
161
162```javascript
163const tmp = require('tmp');
164
165const name = tmp.tmpNameSync();
166console.log('Created temporary filename: ', name);
167```
168
169## Advanced usage
170
171### Asynchronous file creation
172
173Creates a file with mode `0644`, prefix will be `prefix-` and postfix will be `.txt`.
174
175```javascript
176const tmp = require('tmp');
177
178tmp.file({ mode: 0o644, prefix: 'prefix-', postfix: '.txt' }, function _tempFileCreated(err, path, fd) {
179 if (err) throw err;
180
181 console.log('File: ', path);
182 console.log('Filedescriptor: ', fd);
183});
184```
185
186### Synchronous file creation
187
188A synchronous version of the above.
189
190```javascript
191const tmp = require('tmp');
192
193const tmpobj = tmp.fileSync({ mode: 0o644, prefix: 'prefix-', postfix: '.txt' });
194console.log('File: ', tmpobj.name);
195console.log('Filedescriptor: ', tmpobj.fd);
196```
197
198### Controlling the Descriptor
199
200As a side effect of creating a unique file `tmp` gets a file descriptor that is
201returned to the user as the `fd` parameter. The descriptor may be used by the
202application and is closed when the `removeCallback` is invoked.
203
204In some use cases the application does not need the descriptor, needs to close it
205without removing the file, or needs to remove the file without closing the
206descriptor. Two options control how the descriptor is managed:
207
208* `discardDescriptor` - if `true` causes `tmp` to close the descriptor after the file
209 is created. In this case the `fd` parameter is undefined.
210* `detachDescriptor` - if `true` causes `tmp` to return the descriptor in the `fd`
211 parameter, but it is the application's responsibility to close it when it is no
212 longer needed.
213
214```javascript
215const tmp = require('tmp');
216
217tmp.file({ discardDescriptor: true }, function _tempFileCreated(err, path, fd, cleanupCallback) {
218 if (err) throw err;
219 // fd will be undefined, allowing application to use fs.createReadStream(path)
220 // without holding an unused descriptor open.
221});
222```
223
224```javascript
225const tmp = require('tmp');
226
227tmp.file({ detachDescriptor: true }, function _tempFileCreated(err, path, fd, cleanupCallback) {
228 if (err) throw err;
229
230 cleanupCallback();
231 // Application can store data through fd here; the space used will automatically
232 // be reclaimed by the operating system when the descriptor is closed or program
233 // terminates.
234});
235```
236
237### Asynchronous directory creation
238
239Creates a directory with mode `0755`, prefix will be `myTmpDir_`.
240
241```javascript
242const tmp = require('tmp');
243
244tmp.dir({ mode: 0o750, prefix: 'myTmpDir_' }, function _tempDirCreated(err, path) {
245 if (err) throw err;
246
247 console.log('Dir: ', path);
248});
249```
250
251### Synchronous directory creation
252
253Again, a synchronous version of the above.
254
255```javascript
256const tmp = require('tmp');
257
258const tmpobj = tmp.dirSync({ mode: 0750, prefix: 'myTmpDir_' });
259console.log('Dir: ', tmpobj.name);
260```
261
262### mkstemp like, asynchronously
263
264Creates a new temporary directory with mode `0700` and filename like `/tmp/tmp-nk2J1u`.
265
266IMPORTANT NOTE: template no longer accepts a path. Use the dir option instead if you
267require tmp to create your temporary filesystem object in a different place than the
268default `tmp.tmpdir`.
269
270```javascript
271const tmp = require('tmp');
272
273tmp.dir({ template: 'tmp-XXXXXX' }, function _tempDirCreated(err, path) {
274 if (err) throw err;
275
276 console.log('Dir: ', path);
277});
278```
279
280### mkstemp like, synchronously
281
282This will behave similarly to the asynchronous version.
283
284```javascript
285const tmp = require('tmp');
286
287const tmpobj = tmp.dirSync({ template: 'tmp-XXXXXX' });
288console.log('Dir: ', tmpobj.name);
289```
290
291### Asynchronous filename generation
292
293Using `tmpName()` you can create temporary file names asynchronously.
294The function accepts all standard options, e.g. `prefix`, `postfix`, `dir`, and so on.
295
296You can also leave out the options altogether and just call the function with a callback as first parameter.
297
298```javascript
299const tmp = require('tmp');
300
301const options = {};
302
303tmp.tmpName(options, function _tempNameGenerated(err, path) {
304 if (err) throw err;
305
306 console.log('Created temporary filename: ', path);
307});
308```
309
310### Synchronous filename generation
311
312The `tmpNameSync()` function works similarly to `tmpName()`.
313Again, you can leave out the options altogether and just invoke the function without any parameters.
314
315```javascript
316const tmp = require('tmp');
317const options = {};
318const tmpname = tmp.tmpNameSync(options);
319console.log('Created temporary filename: ', tmpname);
320```
321
322## Graceful cleanup
323
324If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the
325temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary
326object removal.
327
328To enforce this, you can call the `setGracefulCleanup()` method:
329
330```javascript
331const tmp = require('tmp');
332
333tmp.setGracefulCleanup();
334```
335
336## Options
337
338All options are optional :)
339
340 * `name`: a fixed name that overrides random name generation, the name must be relative and must not contain path segments
341 * `mode`: the file mode to create with, falls back to `0o600` on file creation and `0o700` on directory creation
342 * `prefix`: the optional prefix, defaults to `tmp`
343 * `postfix`: the optional postfix
344 * `template`: [`mkstemp`][3] like filename template, no default, can be either an absolute or a relative path that resolves
345 to a relative path of the system's default temporary directory, must include `XXXXXX` once for random name generation, e.g.
346 'foo/bar/XXXXXX'. Absolute paths are also fine as long as they are relative to os.tmpdir().
347 Any directories along the so specified path must exist, otherwise a ENOENT error will be thrown upon access,
348 as tmp will not check the availability of the path, nor will it establish the requested path for you.
349 * `dir`: the optional temporary directory that must be relative to the system's default temporary directory.
350 absolute paths are fine as long as they point to a location under the system's default temporary directory.
351 Any directories along the so specified path must exist, otherwise a ENOENT error will be thrown upon access,
352 as tmp will not check the availability of the path, nor will it establish the requested path for you.
353 * `tmpdir`: allows you to override the system's root tmp directory
354 * `tries`: how many times should the function try to get a unique filename before giving up, default `3`
355 * `keep`: signals that the temporary file or directory should not be deleted on exit, default is `false`
356 * In order to clean up, you will have to call the provided `cleanupCallback` function manually.
357 * `unsafeCleanup`: recursively removes the created temporary directory, even when it's not empty. default is `false`
358 * `detachDescriptor`: detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection
359 * `discardDescriptor`: discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection
360
361[1]: http://nodejs.org/
362[2]: https://www.npmjs.com/browse/depended/tmp
363[3]: http://www.kernel.org/doc/man-pages/online/pages/man3/mkstemp.3.html
364[4]: https://raszi.github.io/node-tmp/
365[5]: https://github.com/benjamingr/tmp-promise
366
\No newline at end of file