node.js 生成文件
介绍 (Introduction)
In most of the applications, you need to have some static JSON data with which you can create and test the application without directly using the production data.
在大多数应用程序中,您需要具有一些静态JSON数据,利用它们可以创建和测试应用程序,而无需直接使用生产数据。
If you’re building an e-commerce application, you may need a list of product details with the product name, image, and price to test.
如果要构建电子商务应用程序,则可能需要包含产品名称,图像和价格的产品详细信息列表以进行测试。
If you want to showcase something then first you will need some data to display on the UI.
如果要展示某些东西,则首先需要一些数据才能在UI上显示。
Faker has around 1.4M weekly downloads (as of 19 August, 2020).
Faker每周约有140万次下载(截至2020年8月19日)。
So in this tutorial, you will see how to easily generate any amount of required data using a very popular npm library faker
.
因此,在本教程中,您将看到如何使用非常流行的npm库faker
轻松地生成任何数量的所需数据。
先决条件 (Prerequisites)
You will need the following to complete this tutorial:
您将需要以下内容才能完成本教程:
- Node.js installed locally 本地安装的Node.js
This tutorial was verified with Node
v13.14.0, npm
v6.14.4, faker
v4.1.0, express
v4.17.1, lodash
v4.17.19 and nodemon
v2.0.4
本教程是在验证Node
v13.14.0, npm
v6.14.4, faker
V4.1.0, express
v4.17.1, lodash
v4.17.19和nodemon
V2.0.4
安装 (Installation)
To install the library and other dependencies execute the following command from the terminal:
要安装库和其他依赖项,请从终端执行以下命令:
npm install faker@4.1.0 express@4.17.1 lodash@4.17.19 nodemon@2.0.4
Import the library in the following way
通过以下方式导入库
const faker = require('faker');
使用API (Using APIs)
Following are some of the API categories provided by the library
以下是该库提供的一些API类别
- address 地址
- commerce 商业
- company 公司
- database 数据库
- finance 金融
- hacker 黑客
- helpers 帮手
- image 图片
Each category provides various functions to access the data.
每个类别都提供了访问数据的各种功能。
Get random country, city, state and zip code:
获取随机的国家,城市,州和邮政编码:
const country = faker.address.country(); // Singaporeconst city = faker.address.city(); // Lavernebergconst state = faker.address.state(); // West Virginiaconst zipCode = faker.address.zipCode(); // 57449-4128
Get random product name, price and color:
获取随机的产品名称,价格和颜色:
const product = faker.commerce.product(); // Tableconst price = faker.commerce.price(); // 458.00const color = faker.commerce.color(); // Cyan
Let’s build a simple application in Node.js where you provide a count
of records you want and the application will generate that much data in the JSON format.
让我们在Node.js中构建一个简单的应用程序,在其中提供所需的记录count
,该应用程序将以JSON格式生成大量数据。
最初设定 (Initial Setup)
Create a new folder mock-json-data-generator
and initialize the package.json
file
创建一个新的文件夹mock-json-data-generator
并初始化package.json
文件
mkdir mock-json-data-generatorcd mock-json-data-generatornpm init -y
Now, install the faker
, lodash
, express
and nodemon
npm libraries
现在,安装faker
, lodash
, express
和nodemon
npm库
faker
will be used to generate random mock datafaker
将用于生成随机模拟数据lodash
will be used to execute a function for a certain number of timeslodash
将被用于执行功能一定次数express
will be used to create REST APIsexpress
将用于创建REST APInodemon
will be used to restart the Express.js server if any file content is changed如果任何文件内容发生更改,
nodemon
将用于重新启动Express.js服务器
Execute the following command from the mock-json-data-generator
folder:
从mock-json-data-generator
文件夹执行以下命令:
npm install faker@4.1.0 lodash@4.17.19 express@4.17.1 nodemon@2.0.4
Add a new start script inside package.json
file
在package.json
文件中添加新的启动脚本
"scripts": {
"start": "nodemon index.js"
}
To avoid adding node_modules
folder to git repository create a new .gitignore
file and add the node_modules
entry inside the file
为了避免将node_modules
文件夹添加到git存储库中,请创建一个新的.gitignore
文件,并在该文件内添加node_modules
条目
node_modules
Your package.json
file will look like this now:
您的package.json
文件现在看起来像这样:
获取随机地址列表 (Get a List of Random Addresses)
Create a new index.js
file and add the following code inside it:
创建一个新的index.js
文件,并在其中添加以下代码:
const express = require('express');
const faker = require('faker');
const _ = require('lodash');const app = express();app.get('/address', (req, res) => {
const count = req.query.count;
if (!count) {
return res
.status(400)
.send({ errorMsg: 'count query parameter is missing.' });
}
res.send(
_.times(count, () => {
const address = faker.address;
return {
country: address.country(),
city: address.city(),
state: address.state(),
zipCode: address.zipCode(),
latitude: address.latitude(),
longitude: address.longitude()
};
})
);
});app.listen(3030, () => {
console.log('server started on port 3030');
});
In the above file,
在上面的文件中,
- First, we imported all the required packages 首先,我们导入了所有必需的软件包
Then created an express app by calling the
express
function然后通过调用
express
函数创建一个express应用
const app = express();
3. Then created a /address
route
3.然后创建一个/address
路由
4. Then we’re checking if the user has provided the count
query parameter which specifies the number of records to get back
4.然后,我们检查用户是否提供了count
查询参数,该参数指定要取回的记录数
const count = req.query.count;
if (!count) {
return res
.status(400)
.send({ errorMsg: 'count query parameter is missing.' });
}
5. If the count
does not exist then we are displaying an error message
5.如果count
不存在,那么我们将显示一条错误消息
6. Then we’re using the times
method provided by lodash
which will execute the provided function count
number of times. Lodash
library is optimized for performance so instead of using an array map
method to generate for example 1000 records, we’re using lodash
library so the response will be quicker.
6.然后,我们使用lodash
提供的times
方法,该方法将执行提供的函数count
次数。 Lodash
库针对性能进行了优化,因此我们不使用数组map
方法生成例如1000条记录,而是使用lodash
库,因此响应速度更快。
_.times(count, () => {
const address = faker.address;
return {
country: address.country(),
city: address.city(),
state: address.state(),
zipCode: address.zipCode(),
latitude: address.latitude(),
longitude: address.longitude()
};
})
7. The times
method returns an array. In the provided arrow function, we’re returning an object with the randomly generated values so the output of times
method will be an array of objects with the generated values.
7. times
方法返回一个数组。 在提供的箭头函数中,我们将返回带有随机生成值的对象,因此times
方法的输出将是带有生成值的对象数组。
8. Then we’re sending that result using send
method of response object using res.send
8.然后,使用res.send
使用响应对象的send
方法发送结果
9. Then at the end, we’re starting the Express.js
server on port 3030
9.然后,最后,我们在端口3030
上启动Express.js
服务器。
app.listen(3030, () => {
console.log('server started on port 3030');
});
Now, start the application by executing the following command from the terminal:
现在,通过从终端执行以下命令来启动应用程序:
npm run start
and access the application by visiting http://localhost:3030/address?count=10
并通过访问http:// localhost:3030 / address?count = 10访问该应用程序
Tip: To get the formatted JSON as shown above, you can install the JSON Formatter Google Chrome extension.
提示: 要获取上述格式的JSON,可以安装 JSON Formatter Google Chrome扩展程序。
If you don’t provide the count
query parameter, then you will get an error as can be seen below.
如果不提供count
查询参数,则将出现错误,如下所示。
获取随机产品列表 (Get a List of Random Products)
Add another /products
route to get the list of products.
添加另一个/products
路线以获取产品列表。
app.get('/products', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const commerce = faker.commerce;
return {
product: commerce.product(),
price: commerce.price(),
color: commerce.color()
};
})
);
});
In this code, instead of faker.address
, we’ve used faker.commerce
and its related methods.
在此代码中,我们使用了faker.commerce
及其相关方法,而不是faker.address
。
获取随机图像列表 (Get a List of Random Images)
Add another /images
route to get the list of images.
添加另一个/images
路由以获取图像列表。
app.get('/images', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const image = faker.image;
return {
image: image.image(),
avatar: image.avatar()
};
})
);
});
In this code, we’ve used faker.image
and its related methods.
在此代码中,我们使用了faker.image
及其相关方法。
获取随机单词列表 (Get a List of Random Words)
Add another /random
route to get the list of random words.
添加另一个/random
路由以获取随机单词的列表。
app.get('/random', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const random = faker.random;
return {
word: random.word(),
words: random.words()
};
})
);
});
In this code, we’ve used faker.random
and its related methods.
在这段代码中,我们使用了faker.random
及其相关方法。
获取随机用户列表 (Get a List of Random Users)
Add another /users
route to get the list of random users.
添加另一个/users
路由以获取随机用户列表。
app.get('/users', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const user = faker.name;
return {
firstName: user.firstName(),
lastName: user.lastName(),
jobTitle: user.jobTitle()
};
})
);
});
In this code, we’ve used faker.name
and its related methods.
在这段代码中,我们使用了faker.name
及其相关方法。
获取随机Lorem输液文字列表 (Get a List of Random Lorem Ipsum Text)
Add another /lorem
route to get the list of random lorem ipsum paragraphs.
添加另一个/lorem
路由以获取随机lorem ipsum段落的列表。
app.get('/lorem', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const lorem = faker.lorem;
return {
paragraph: lorem.paragraph(),
sentence: lorem.sentence(),
paragraphs: lorem.paragraphs()
};
})
);
});
In this code, we’ve used faker.lorem
and its related methods.
在此代码中,我们使用了faker.lorem
及其相关方法。
获取随机用户信息列表 (Get a List of Random User Information)
Faker
library also provides a set of helpers like createCard
, userCard
, createTransaction
.
Faker
库还提供了一组帮助器,例如createCard
, userCard
, createTransaction
。
Add another /userCard
route to get the list of the random card of user information like name, email, address, website, company.
添加另一个/userCard
路由以获取用户信息(例如名称,电子邮件,地址,网站,公司)的随机卡列表。
app.get('/userCard', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const helpers = faker.helpers;
return {
userCard: helpers.userCard()
};
})
);
});
In this code, we’ve used faker.helpers
and its userCard
method.
在这段代码中,我们使用了faker.helpers
及其userCard
方法。
In addition to the above user details, If we want the user's posts and transaction details, we can use the createCard
helper method
除了上面的用户详细信息,如果我们需要用户的帖子和交易详细信息,我们可以使用createCard
helper方法
Add another /createCard
route to get the data of users posts and transactions in addition to the other details
除了其他详细信息之外,添加另一个/createCard
路由以获取用户帖子和交易的数据
app.get('/createCard', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const helpers = faker.helpers;
return {
createCard: helpers.createCard()
};
})
);
});
In this code, we’ve used faker.helpers
and its createCard
method.
在这段代码中,我们使用了faker.helpers
及其createCard
方法。
Faker
provides a lot of other details which you can check at this url.
Faker
提供了许多其他详细信息,您可以在此url进行检查。
结论 (Conclusion)
As you have seen, the faker library provides a lot of API functions to easily generate random data. It’s also very useful when you want to build something quickly without wasting hours of time for creating the data to work with.
如您所见,fakerr库提供了许多API函数,可轻松生成随机数据。 当您要快速构建某些内容而又不浪费数小时的时间来创建要使用的数据时,它也非常有用。
You can find the complete source code for this application here.
您可以在此处找到此应用程序的完整源代码。
That’s it for today. I hope you learned something new.
今天就这样。 我希望你学到了一些新东西。
node.js 生成文件