Reputation: 1141
So I'm working on this project where I export some data files with sensitive information and I want to generate uuid for each of them. I'm using node uuid module but every time I run my function the UUID is actually the same and old file gets overwritten with a new file as its UUID is the same. Here's snipped of my code:
var nodeUuid = require('node-uuid');
var uuid = nodeUuid.v4();
function createFile(){
var filename = 'reports-'+uuid+'.txt';
}
...
createFile();
So every time I call function createFile() I get the same UUID and my files are getting over-written, any idea how I could actually generate unique id for every new file?
Upvotes: 0
Views: 5290
Reputation: 2414
I might be late to the party, but you can do this without a library:
The script below is the minified version of node-uuid
v4 only library
import { default as crypto } from 'crypto'
class _Uuid {
static v4(offset = 0){
let byteToHex = [], rnds = crypto.randomBytes(16)
rnds[6] = (rnds[6] & 0x0f) | 0x40 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[8] = (rnds[8] & 0x3f) | 0x80 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1) }
return ([byteToHex[rnds[offset++]], byteToHex[rnds[offset++]], byteToHex[rnds[offset++]], byteToHex[rnds[offset++]], '-', byteToHex[rnds[offset++]], byteToHex[rnds[offset++]], '-', byteToHex[rnds[offset++]], byteToHex[rnds[offset++]], '-', byteToHex[rnds[offset++]], byteToHex[rnds[offset++]], '-', byteToHex[rnds[offset++]], byteToHex[rnds[offset++]], byteToHex[rnds[offset++]], byteToHex[rnds[offset++]], byteToHex[rnds[offset++]], byteToHex[rnds[offset++]]]).join('')
}
}
const v4 = _Uuid.v4
export { v4 as default }
import { default as uuid } from '_Uuid'
uuid() // 3ceb4f8f-cef9-400f-a394-80da0334273b
This is an ES6 script that uses the bundled crypto library in node and facilitates simple, fast generation of RFC4122 compliant v4 UUIDS. Source Code
Upvotes: 0
Reputation: 13567
Currently you're only generating a single UUID when the script is first loaded. To generate a new one each time you call createFile()
, simply move the generation inside your createFile()
function:
var nodeUuid = require('node-uuid');
function createFile(){
var uuid = nodeUuid.v4();
var filename = 'reports-'+uuid+'.txt';
}
...
createFile();
Upvotes: 1
Reputation: 8263
Move v4()
call in to the function
function createFile(){
var uuid = nodeUuid.v4();
var filename = 'reports-'+uuid+'.txt';
}
Upvotes: 6