UNPKG

1.23 kBJavaScriptView Raw
1"use strict";
2
3const fs = require('fs');
4const path = require('path');
5const os = require('os');
6const crypto = require('crypto');
7
8var exitListenerAttached = false;
9var filesToDelete = [];
10
11function deleteOnExit(file_path) {
12 if(!exitListenerAttached) {
13 process.on('exit', cleanupFilesSync);
14 process.on('fsgc', cleanupFilesSync); //force cleanup
15
16 //makes sure exit is called event on sigint \o/
17 process.on('SIGINT', process.exit);
18 exitListenerAttached = true;
19 }
20
21 filesToDelete.push(file_path);
22}
23
24
25function cleanupFilesSync() {
26 var toDelete;
27 while((toDelete = filesToDelete.shift()) !== undefined) {
28 try {
29 if(fs.existsSync(toDelete))
30 fs.unlinkSync(toDelete);
31 } catch(err) {} //maybe buzy
32 }
33}
34
35
36function tmppath(ext, trash, len) {
37 ext = ext || "tmp"; len = len || 8;
38 if(trash === undefined) trash = true;
39
40 var body = crypto.randomBytes(len).toString('base64').replace(/\//g, '+').substr(0, len);
41 var fname = ext + "-" + body + "." + ext;
42 var file_path = path.join(os.tmpdir(), fname);
43
44 var fullpath = fs.existsSync(file_path) ? tmppath(ext, trash, len + 1) : file_path;
45 if(trash)
46 deleteOnExit(fullpath);
47
48 return fullpath;
49}
50
51module.exports = tmppath;