Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80679 views
1
/*
2
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
3
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
4
*/
5
6
var util = require('util'),
7
path = require('path'),
8
os = require('os'),
9
fs = require('fs'),
10
mkdirp = require('mkdirp'),
11
Store = require('./index');
12
13
function makeTempDir() {
14
var dir = path.join(os.tmpDir ? os.tmpDir() : /* istanbul ignore next */ (process.env.TMPDIR || '/tmp'), 'ts' + new Date().getTime());
15
mkdirp.sync(dir);
16
return dir;
17
}
18
/**
19
* a `Store` implementation using temporary files.
20
*
21
* Usage
22
* -----
23
*
24
* var store = require('istanbul').Store.create('tmp');
25
*
26
*
27
* @class TmpStore
28
* @extends Store
29
* @module store
30
* @param {Object} opts Optional.
31
* @param {String} [opts.tmp] a pre-existing directory to use as the `tmp` directory. When not specified, a random directory
32
* is created under `os.tmpDir()`
33
* @constructor
34
*/
35
function TmpStore(opts) {
36
opts = opts || {};
37
this.tmp = opts.tmp || makeTempDir();
38
this.map = {};
39
this.seq = 0;
40
this.prefix = 't' + new Date().getTime() + '-';
41
}
42
43
TmpStore.TYPE = 'tmp';
44
util.inherits(TmpStore, Store);
45
46
Store.mix(TmpStore, {
47
generateTmpFileName: function () {
48
this.seq += 1;
49
return this.prefix + this.seq + '.tmp';
50
},
51
52
set: function (key, contents) {
53
var tmpFile = this.generateTmpFileName();
54
fs.writeFileSync(tmpFile, contents, 'utf8');
55
this.map[key] = tmpFile;
56
},
57
58
get: function (key) {
59
var tmpFile = this.map[key];
60
if (!tmpFile) { throw new Error('Unable to find tmp entry for [' + tmpFile + ']'); }
61
return fs.readFileSync(tmpFile, 'utf8');
62
},
63
64
hasKey: function (key) {
65
return !!this.map[key];
66
},
67
68
keys: function () {
69
return Object.keys(this.map);
70
},
71
72
dispose: function () {
73
var map = this.map;
74
Object.keys(map).forEach(function (key) {
75
fs.unlinkSync(map[key]);
76
});
77
this.map = {};
78
}
79
});
80
81
module.exports = TmpStore;
82
83