UNPKG

8.27 kBMarkdownView Raw
1node-temp
2=========
3
4Temporary files, directories, and streams for Node.js.
5
6Handles generating a unique file/directory name under the appropriate
7system temporary directory, changing the file to an appropriate mode,
8and supports automatic removal (if asked)
9
10`temp` has a similar API to the `fs` module.
11
12Node.js Compatibility
13---------------------
14
15Supports v4.0.0+.
16
17[![Build Status](https://travis-ci.org/bruce/node-temp.png)](https://travis-ci.org/bruce/node-temp)
18
19Please let me know if you have problems running it on a later version of Node.js or
20have platform-specific problems.
21
22Installation
23------------
24
25Install it using [npm](http://github.com/isaacs/npm):
26
27 $ npm install temp
28
29Or get it directly from:
30http://github.com/bruce/node-temp
31
32Synopsis
33--------
34
35You can create temporary files with `open` and `openSync`, temporary
36directories with `mkdir` and `mkdirSync`, or you can get a unique name
37in the system temporary directory with `path`.
38
39Working copies of the following examples can be found under the
40`examples` directory.
41
42### Temporary Files
43
44To create a temporary file use `open` or `openSync`, passing
45them an optional prefix, suffix, or both (see below for details on
46affixes). The object passed to the callback (or returned) has
47`path` and `fd` keys:
48
49```javascript
50{ path: "/path/to/file",
51, fd: theFileDescriptor
52}
53```
54
55In this example we write to a temporary file and call out to `grep` and
56`wc -l` to determine the number of time `foo` occurs in the text. The
57temporary file is chmod'd `0600` and cleaned up automatically when the
58process at exit (because `temp.track()` is called):
59
60```javascript
61var temp = require('temp'),
62 fs = require('fs'),
63 util = require('util'),
64 exec = require('child_process').exec;
65
66// Automatically track and cleanup files at exit
67temp.track();
68
69// Fake data
70var myData = "foo\nbar\nfoo\nbaz";
71
72// Process the data (note: error handling omitted)
73temp.open('myprefix', function(err, info) {
74 if (!err) {
75 fs.write(info.fd, myData);
76 fs.close(info.fd, function(err) {
77 exec("grep foo '" + info.path + "' | wc -l", function(err, stdout) {
78 util.puts(stdout.trim());
79 });
80 });
81 }
82});
83```
84
85### Want Cleanup? Make sure you ask for it.
86
87As noted in the example above, if you want temp to track the files and
88directories it creates and handle removing those files and directories
89on exit, you must call `track()`. The `track()` function is chainable,
90and it's recommended that you call it when requiring the module.
91
92```javascript
93var temp = require("temp").track();
94```
95
96Why is this necessary? In pre-0.6 versions of temp, tracking was
97automatic. While this works great for scripts and
98[Grunt tasks](http://gruntjs.com/), it's not so great for long-running
99server processes. Since that's arguably what Node.js is _for_, you
100have to opt-in to tracking.
101
102But it's easy.
103
104#### Cleanup anytime
105
106When tracking, you can run `cleanup()` and `cleanupSync()` anytime
107(`cleanupSync()` will be run for you on process exit). An object will
108be returned (or passed to the callback) with cleanup counts and
109the file/directory tracking lists will be reset.
110
111```javascript
112> temp.cleanupSync();
113{ files: 1,
114 dirs: 0 }
115```
116
117```javascript
118> temp.cleanup(function(err, stats) {
119 console.log(stats);
120 });
121{ files: 1,
122 dirs: 0 }
123```
124
125Note: If you're not tracking, an error ("not tracking") will be passed
126to the callback.
127
128### Temporary Directories
129
130To create a temporary directory, use `mkdir` or `mkdirSync`, passing
131it an optional prefix, suffix, or both (see below for details on affixes).
132
133In this example we create a temporary directory, write to a file
134within it, call out to an external program to create a PDF, and read
135the result. While the external process creates a lot of additional
136files, the temporary directory is removed automatically at exit (because
137`temp.track()` is called):
138
139```javascript
140var temp = require('temp'),
141 fs = require('fs'),
142 util = require('util'),
143 path = require('path'),
144 exec = require('child_process').exec;
145
146// Automatically track and cleanup files at exit
147temp.track();
148
149// For use with ConTeXt, http://wiki.contextgarden.net
150var myData = "\\starttext\nHello World\n\\stoptext";
151
152temp.mkdir('pdfcreator', function(err, dirPath) {
153 var inputPath = path.join(dirPath, 'input.tex')
154 fs.writeFile(inputPath, myData, function(err) {
155 if (err) throw err;
156 process.chdir(dirPath);
157 exec("texexec '" + inputPath + "'", function(err) {
158 if (err) throw err;
159 fs.readFile(path.join(dirPath, 'input.pdf'), function(err, data) {
160 if (err) throw err;
161 sys.print(data);
162 });
163 });
164 });
165});
166```
167
168### Temporary Streams
169
170To create a temporary WriteStream, use 'createWriteStream', which sits
171on top of `fs.createWriteStream`. The return value is a
172`fs.WriteStream` with a `path` property containing the temporary file
173path for the stream. The `path` is registered for removal when
174`temp.cleanup` is called (because `temp.track()` is called).
175
176```javascript
177var temp = require('temp');
178
179// Automatically track and cleanup files at exit
180temp.track();
181
182var stream = temp.createWriteStream();
183// stream.path contains the temporary file path for the stream
184stream.write("Some data");
185// Maybe do some other things
186stream.end();
187```
188
189### Affixes
190
191You can provide custom prefixes and suffixes when creating temporary
192files and directories. If you provide a string, it is used as the prefix
193for the temporary name. If you provide an object with `prefix`,
194`suffix` and `dir` keys, they are used for the temporary name.
195
196Here are some examples:
197
198* `"aprefix"`: A simple prefix, prepended to the filename; this is
199 shorthand for:
200* `{prefix: "aprefix"}`: A simple prefix, prepended to the filename
201* `{suffix: ".asuffix"}`: A suffix, appended to the filename
202 (especially useful when the file needs to be named with specific
203 extension for use with an external program).
204* `{prefix: "myprefix", suffix: "mysuffix"}`: Customize both affixes
205* `{dir: path.join(os.tmpdir(), "myapp")}`: default prefix and suffix
206 within a new temporary directory.
207* `null`: Use the defaults for files and directories (prefixes `"f-"`
208 and `"d-"`, respectively, no suffixes).
209
210In this simple example we read a `pdf`, write it to a temporary file with
211a `.pdf` extension, and close it.
212
213```javascript
214var fs = require('fs'),
215 temp = require('temp');
216
217fs.readFile('/path/to/source.pdf', function(err, data) {
218 temp.open({suffix: '.pdf'}, function(err, info) {
219 if (err) throw err;
220 fs.write(info.fd, data);
221 fs.close(info.fd, function(err) {
222 if (err) throw err;
223 // Do something with the file
224 });
225 });
226});
227```
228
229### Just a path, please
230
231If you just want a unique name in your temporary directory, use
232`path`:
233
234```javascript
235var fs = require('fs');
236var tempName = temp.path({suffix: '.pdf'});
237// Do something with tempName
238```
239
240Note: The file isn't created for you, and the mode is not changed -- and it
241will not be removed automatically at exit. If you use `path`, it's
242all up to you.
243
244Using it with Grunt
245-------------------
246
247If you want to use the module with [Grunt](http://gruntjs.com/), make sure you
248use `async()` in your Gruntfile:
249
250```javascript
251module.exports = function (grunt) {
252 var temp = require("temp");
253 temp.track(); // Cleanup files, please
254 grunt.registerTask("temptest", "Testing temp", function() {
255
256 var done = this.async(); // Don't forget this!
257
258 grunt.log.writeln("About to write a file...");
259 temp.open('tempfile', function(err, info) {
260 // File writing shenanigans here
261 grunt.log.writeln("Wrote a file!")
262
263 done(); // REALLY don't forget this!
264
265 });
266 });
267};
268```
269
270For more information, see the [Grunt FAQ](http://gruntjs.com/frequently-asked-questions#why-doesn-t-my-asynchronous-task-complete).
271
272Testing
273-------
274
275```sh
276$ npm test
277```
278
279Contributing
280------------
281
282You can find the repository at:
283http://github.com/bruce/node-temp
284
285Issues/Feature Requests can be submitted at:
286http://github.com/bruce/node-temp/issues
287
288I'd really like to hear your feedback, and I'd love to receive your
289pull-requests!
290
291Copyright
292---------
293
294Copyright (c) 2010-2014 Bruce Williams. This software is licensed
295under the MIT License, see LICENSE for details.