UNPKG

1.79 kBJavaScriptView Raw
1var common = require('./common');
2var os = require('os');
3var fs = require('fs');
4
5common.register('tempdir', _tempDir, {
6 allowGlobbing: false,
7 wrapOutput: false,
8});
9
10// Returns false if 'dir' is not a writeable directory, 'dir' otherwise
11function writeableDir(dir) {
12 if (!dir || !fs.existsSync(dir)) return false;
13
14 if (!common.statFollowLinks(dir).isDirectory()) return false;
15
16 var testFile = dir + '/' + common.randomFileName();
17 try {
18 fs.writeFileSync(testFile, ' ');
19 common.unlinkSync(testFile);
20 return dir;
21 } catch (e) {
22 /* istanbul ignore next */
23 return false;
24 }
25}
26
27
28//@
29//@ ### tempdir()
30//@
31//@ Examples:
32//@
33//@ ```javascript
34//@ var tmp = tempdir(); // "/tmp" for most *nix platforms
35//@ ```
36//@
37//@ Searches and returns string containing a writeable, platform-dependent temporary directory.
38//@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir).
39function _tempDir() {
40 var state = common.state;
41 if (state.tempDir) return state.tempDir; // from cache
42
43 state.tempDir = writeableDir(os.tmpdir()) ||
44 writeableDir(process.env.TMPDIR) ||
45 writeableDir(process.env.TEMP) ||
46 writeableDir(process.env.TMP) ||
47 writeableDir(process.env.Wimp$ScrapDir) || // RiscOS
48 writeableDir('C:\\TEMP') || // Windows
49 writeableDir('C:\\TMP') || // Windows
50 writeableDir('\\TEMP') || // Windows
51 writeableDir('\\TMP') || // Windows
52 writeableDir('/tmp') ||
53 writeableDir('/var/tmp') ||
54 writeableDir('/usr/tmp') ||
55 writeableDir('.'); // last resort
56
57 return state.tempDir;
58}
59module.exports = _tempDir;