tempdir.js 1.8 KB

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