我想知道是否有办法设置虚假数据(信息),如名称和电子邮件,并将其存储在JSON文件中。我知道faker可以和node和NPM一起用来在JS中创建假数据但是用JSON呢?
答案 0 :(得分:0)
var faker = require('faker');
var fs = require('fs');
var data = {};
data.name = faker.name.findName();
data.email = faker.internet.email();
fs.writeFile('data.json', JSON.stringify(data), (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
答案 1 :(得分:0)
再有example个生成十个用户,并将它们写入data.json
文件中。
employees.js
let faker = require('faker');
let fs = require('fs');
function generateEmployees() {
let employees = [];
for (let id = 1; id <= 10; id++) {
let firstName = faker.name.firstName();
let lastName = faker.name.lastName();
let email = faker.internet.email();
employees.push({
id: id,
first_name: firstName,
last_name: lastName,
email: email,
});
}
return { employees: employees };
}
module.exports = generateEmployees;
let dataObj = generateEmployees();
fs.writeFileSync('data.json', JSON.stringify(dataObj, null, '\t'));
$ json-server employees.js
现在,您可以单击资源链接以查看结果。
受@le_m的启发,您无需使用for循环即可生成虚拟数据:
let faker = require('faker');
let fs = require('fs');
const generateEmployee = () => {
return {
id: faker.random.uuid(),
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
email: faker.internet.email(),
};
};
const generateEmployees = (numUsers) => {
return Array.from({ length: numUsers }, generateEmployee);
};
let dataObj = generateEmployees(10);
fs.writeFileSync('data.json', JSON.stringify(dataObj, null, '\t'));
然后,只需使用以下命令启动服务器:
$ node employees.js