UNPKG

7.88 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 v0.6.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 fs.write(info.fd, myData);
75 fs.close(info.fd, function(err) {
76 exec("grep foo '" + info.path + "' | wc -l", function(err, stdout) {
77 util.puts(stdout.trim());
78 });
79 });
80});
81```
82
83### Want Cleanup? Make sure you ask for it.
84
85As noted in the example above, if you want temp to track the files and directories
86it creates and handle removing those files and directories on exit, you must call `track()`.
87It's recommended that you do this immediately after requiring the module.
88
89```javascript
90var temp = require("temp");
91temp.track();
92```
93
94Why is this necessary? In pre-0.6 versions of temp, tracking was automatic. While this works
95great for scripts and [Grunt tasks](http://gruntjs.com/), it's not so great for long-running
96server processes. Since that's arguably what Node.js is _for_, you have to opt-in to tracking.
97
98But it's easy.
99
100#### Cleanup anytime
101
102When tracking, you can `cleanup()` anytime. An object will be returned with cleanup statistics
103and the file/directory lists will be reset.
104
105```javascript
106> temp.cleanup();
107{ files: { removed: 1, missing: 0 },
108 dirs: { removed: 0, missing: 0 } }
109```
110
111Note: If you're not tracking, `false` will be returned.
112
113### Temporary Directories
114
115To create a temporary directory, use `mkdir` or `mkdirSync`, passing
116it an optional prefix, suffix, or both (see below for details on affixes).
117
118In this example we create a temporary directory, write to a file
119within it, call out to an external program to create a PDF, and read
120the result. While the external process creates a lot of additional
121files, the temporary directory is removed automatically at exit (because
122`temp.track()` is called):
123
124```javascript
125var temp = require('../lib/temp'),
126 fs = require('fs'),
127 util = require('util'),
128 path = require('path'),
129 exec = require('child_process').exec;
130
131// Automatically track and cleanup files at exit
132temp.track();
133
134// For use with ConTeXt, http://wiki.contextgarden.net
135var myData = "\\starttext\nHello World\n\\stoptext";
136
137temp.mkdir('pdfcreator', function(err, dirPath) {
138 var inputPath = path.join(dirPath, 'input.tex')
139 fs.writeFile(inputPath, myData, function(err) {
140 if (err) throw err;
141 process.chdir(dirPath);
142 exec("texexec '" + inputPath + "'", function(err) {
143 if (err) throw err;
144 fs.readFile(path.join(dirPath, 'input.pdf'), function(err, data) {
145 if (err) throw err;
146 sys.print(data);
147 });
148 });
149 });
150});
151```
152
153### Temporary Streams
154
155To create a temporary WriteStream, use 'createWriteStream', which sits
156on top of `fs.createWriteStream`. The return value is a
157`fs.WriteStream` whose `path` is registered for removal when
158`temp.cleanup` is called (because `temp.track()` is called).
159
160```javascript
161var temp = require('temp');
162
163// Automatically track and cleanup files at exit
164temp.track();
165
166var stream = temp.createWriteStream();
167stream.write("Some data");
168// Maybe do some other things
169stream.end();
170```
171
172### Affixes
173
174You can provide custom prefixes and suffixes when creating temporary
175files and directories. If you provide a string, it is used as the prefix
176for the temporary name. If you provide an object with `prefix`,
177`suffix` and `dir` keys, they are used for the temporary name.
178
179Here are some examples:
180
181* `"aprefix"`: A simple prefix, prepended to the filename; this is
182 shorthand for:
183* `{prefix: "aprefix"}`: A simple prefix, prepended to the filename
184* `{suffix: ".asuffix"}`: A suffix, appended to the filename
185 (especially useful when the file needs to be named with specific
186 extension for use with an external program).
187* `{prefix: "myprefix", suffix: "mysuffix"}`: Customize both affixes
188* `{dir: path.join(os.tmpDir()), "myapp"}`: default prefix and suffix
189 within a new temporary directory.
190* `null`: Use the defaults for files and directories (prefixes `"f-"`
191 and `"d-"`, respectively, no suffixes).
192
193In this simple example we read a `pdf`, write it to a temporary file with
194a `.pdf` extension, and close it.
195
196```javascript
197var fs = require('fs'),
198 temp = require('temp');
199
200fs.readFile('/path/to/source.pdf', function(err, data) {
201 temp.open({suffix: '.pdf'}, function(err, info) {
202 if (err) throw err;
203 fs.write(info.fd, contents);
204 fs.close(info.fd, function(err) {
205 if (err) throw err;
206 // Do something with the file
207 });
208 });
209});
210```
211
212### Just a path, please
213
214If you just want a unique name in your temporary directory, use
215`path`:
216
217```javascript
218var fs = require('fs');
219var tempName = temp.path({suffix: '.pdf'});
220// Do something with tempName
221```
222
223Note: The file isn't created for you, and the mode is not changed -- and it
224will not be removed automatically at exit. If you use `path`, it's
225all up to you.
226
227Using it with Grunt
228-------------------
229
230If you want to use the module with [Grunt](http://gruntjs.com/), make sure you
231use `async()` in your Gruntfile:
232
233```javascript
234module.exports = function (grunt) {
235 var temp = require("temp");
236 temp.track(); // Cleanup files, please
237 grunt.registerTast("temptest", "Testing temp", function() {
238
239 var done = this.async(); // Don't forget this!
240
241 grunt.log.writeln("About to write a file...");
242 temp.open('tempfile', function(err, info) {
243 // File writing shenanigans here
244 grunt.log.writeln("Wrote a file!")
245
246 done(); // REALLY don't forget this!
247
248 });
249 });
250};
251```
252
253For more information, see the [Grunt FAQ](http://gruntjs.com/frequently-asked-questions#why-doesn-t-my-asynchronous-task-complete).
254
255Testing
256-------
257
258For now, run `test/temp-test.js`:
259
260 $ node test/temp-test.js
261
262Contributing
263------------
264
265You can find the repository at:
266http://github.com/bruce/node-temp
267
268Issues/Feature Requests can be submitted at:
269http://github.com/bruce/node-temp/issues
270
271I'd really like to hear your feedback, and I'd love to receive your
272pull-requests!
273
274Copyright
275---------
276
277Copyright (c) 2010-2012 Bruce Williams. See LICENSE for details.