-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (54 loc) · 1.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
var uuid = require('node-uuid')
, fs = require('fs');
// Param redis: Redis client
// Param namespace: A prefix for the file name
// Param createFile: default true, creates an empty file in generated path
// Param callback: Method to be called when file path is creaetd.
// Accepts an error, and the fPath
// The purpose of this wrapper is to create a unique blob name in redis
// Returns a file path to use
// User is responsible for cleaning the filename from Redis
// and clean the touched file from the FS
//
module.exports.createUniquePath = function(redis, namespace, createFile, callback) {
if (namespace == undefined) {
namespace = "tmp";
}
if (createFile == undefined) {
createFile = true;
}
var touchFile = function(fPath, callback) {
fs.writeFile(fPath, "", function(err) {
if (err) {
return callback(err);
}
callback();
});
}
var inner = function() {
// Generate random filename
var fPath = "/tmp/" + namespace + uuid.v4();
// Use this file path as a unique id
// If the file path is unique in redis, then return
redis.setnx('blob:' + fPath, "", function(err, result) {
if (err) {
return callback(err);
}
if (result == 1) {
if (createFile) {
touchFile(fPath, function(err) {
if (err) {
return callback(err);
}
callback(null, fPath);
});
} else {
callback(null, fPath);
}
} else {
inner();
}
});
}
inner();
}