faker.js tutorial
Javascript Node.js

Generate Random Fake Name with Faker.js

If you’re looking for javascript library to generate fake name or dummy personal info such as email, street address, company and etc. Faker.js is the one you can’t missed.

Faker.js allows you to generate a various type of random data. Such as names , email address, profile avatar, street address, bank account, company, job title and so much more. This is very useful for driving the test or populating the data to your mock website. Let’s go check it out!

Setup

Faker.js is available for both server-side and browser-side. So if you want to implement it for a web browser just downlaod the latest release from github and plug it in to your web page.

var faker = require('faker');
//or
<script src="faker.min.js"></script>

Usage

Using faker.js is very easy. Just call any API method that you want to use. For example if you want to random a full name  or email address, just call

var randomName = faker.name.findName(); // Harry Potter
var randomEmail = faker.internet.email(); // [email protected]

Now let’s add some more code to show the power of faker.js. I’m going to random a person name and the company and avatar. I’ll use jQuery to create a new div element for each person and append it to page.

<div id="wrapper">
</div>
<script>
for (var i=0 ;i<10;i++) {
  jQuery('<div/>', {
  text: faker.name.findName() + '-' + faker.company.companyName()
  }).appendTo('#wrapper');

  jQuery('<img/>', {
  src: faker.image.avatar()
  }).appendTo('#wrapper');
}
</script>

And here is the result

Another cool feature of faker.js is that you can switch between the locale easily. For example if I want to random a korean person name, just use

faker.locale = 'ko';

And the result…

Faker.js is also very useful to generate a large quantity of data which you can use it to populate the database for testing purpose. Here is the example of Faker.js combined with Node.js

var faker = require('faker');
var fs = require('fs');
var str = "";

for (var i=0;i<100;i++)
  str += faker.name.firstName() + '\t' + faker.name.lastName() + '\t' + faker.internet.email() + '\t' + faker.name.jobTitle() + '\t' + faker.random.locale() +"\r\n";

fs.writeFile('c:/test.txt',str,function(err) { 
  if(err) return console.log(err); else console.log('file saved')
});

And within 5 minutes, I now have a text file containing the list of random person names ,email addresses, job title and nationality. Which can be opened in excel – ready to be imported to any databases.

See all of these in action on our video tutorial on Youtube.

So that’s all about basic of Faker.js. Don’t forget to subscribe our Youtube Channel for more interesting javascript library and other tutorials!

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

error: