1 | "use strict";
|
2 |
|
3 | const fs = require('fs');
|
4 | const path = require('path');
|
5 | const os = require('os');
|
6 | const crypto = require('crypto');
|
7 |
|
8 | var exitListenerAttached = false;
|
9 | var filesToDelete = [];
|
10 |
|
11 | function deleteOnExit(file_path) {
|
12 | if(!exitListenerAttached) {
|
13 | process.on('exit', cleanupFilesSync);
|
14 | process.on('fsgc', cleanupFilesSync);
|
15 |
|
16 |
|
17 | process.on('SIGINT', process.exit);
|
18 | exitListenerAttached = true;
|
19 | }
|
20 |
|
21 | filesToDelete.push(file_path);
|
22 | }
|
23 |
|
24 |
|
25 | function cleanupFilesSync() {
|
26 | var toDelete;
|
27 | while((toDelete = filesToDelete.shift()) !== undefined) {
|
28 | try {
|
29 | if(fs.existsSync(toDelete))
|
30 | fs.unlinkSync(toDelete);
|
31 | } catch(err) {}
|
32 | }
|
33 | }
|
34 |
|
35 |
|
36 | function 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 |
|
51 | module.exports = tmppath;
|