UNPKG

2.25 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// Variable to cache the tempdir value for successive lookups.
28var cachedTempDir;
29
30//@
31//@ ### tempdir()
32//@
33//@ Examples:
34//@
35//@ ```javascript
36//@ var tmp = tempdir(); // "/tmp" for most *nix platforms
37//@ ```
38//@
39//@ Searches and returns string containing a writeable, platform-dependent temporary directory.
40//@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir).
41function _tempDir() {
42 if (cachedTempDir) return cachedTempDir;
43
44 cachedTempDir = writeableDir(os.tmpdir()) ||
45 writeableDir(process.env.TMPDIR) ||
46 writeableDir(process.env.TEMP) ||
47 writeableDir(process.env.TMP) ||
48 writeableDir(process.env.Wimp$ScrapDir) || // RiscOS
49 writeableDir('C:\\TEMP') || // Windows
50 writeableDir('C:\\TMP') || // Windows
51 writeableDir('\\TEMP') || // Windows
52 writeableDir('\\TMP') || // Windows
53 writeableDir('/tmp') ||
54 writeableDir('/var/tmp') ||
55 writeableDir('/usr/tmp') ||
56 writeableDir('.'); // last resort
57
58 return cachedTempDir;
59}
60
61// Indicates if the tempdir value is currently cached. This is exposed for tests
62// only. The return value should only be tested for truthiness.
63function isCached() {
64 return cachedTempDir;
65}
66
67// Clears the cached tempDir value, if one is cached. This is exposed for tests
68// only.
69function clearCache() {
70 cachedTempDir = undefined;
71}
72
73module.exports.tempDir = _tempDir;
74module.exports.isCached = isCached;
75module.exports.clearCache = clearCache;