15

I am developing an app, in which users can post pics. So I want to ensure that every time the pic gets unique name. In PHP I use to concatenate timestamp with userId. But in node.js I am not getting the method to convert timestamp to string. So kindly suggest a way to ensure that my files don't get duplicate names.

Tirthankar Kundu
  • 695
  • 3
  • 9
  • 19

4 Answers4

20

One of the solutions would be to use UUID for a file name. But that of course depends on your applications requirements or constraints (naming convention etc.). However, if UUID as a file name would be acceptable, I recommend using node-uuid library (very easy to use!).

Sample code:

var uuidv4 = require('uuid/v4');
var filename = uuidv4() + '.png'

It is safe to use UUID as a unique identifier. You can find more on that on SO e.g. How unique is UUID?

Alternative solution (where name uniqueness is a requirement) would be to use another node.js library: flake-idgen which generates conflict-free ids based on the current timestamp. That solution guarantees unique numbers.

The solution is also very efficient, allows to generate up to 4096 ids in a millisecond per generator (you can have up to 1024 unique generators).

I hope that will help.

Arjun Yelamanchili
  • 577
  • 1
  • 3
  • 16
Tom
  • 26,212
  • 21
  • 100
  • 111
  • This does not answer the question how to get a timestamp as a string, but is way better for generating unique file names. – TheHippo Dec 11 '13 at 11:49
  • @TheHippo that's true I did not provided answer to concatenate timestamp with a user id. I focused on `... suggest a way to ensure that my files don't get duplicate names` - different approach which is, as you said, better alternative ;) Regards. – Tom Dec 11 '13 at 12:23
8

In node:

timestamp = new Date().getTime().toString();
damphat
  • 18,246
  • 8
  • 45
  • 59
5

If you want to use timestamp uuid's use this

var uuid = require('uuid');

// Generate a v1 (time-based) id 
uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

// Generate a v4 (random) id 
uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 
Adrian Kremer
  • 94
  • 1
  • 3
0
//imageExt your file extension;    
const imageName = Date.now() + imageExt;

Date.now() return time in milliseconds since 1st January 1970, if the server is fast enough to process 2 images in less than 1 millisecond you will loose an image because they both will have the same name,

the better way to do this is by using uuidv4

const { v4: uuidv4 } = require("uuid");

const imageName = uuidv4() + imageExt; // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed.jpg'

uuid chance for name colision is extremely unlikely to happen.