node.js 生成文件_如何使用Node.js在几秒钟内生成模拟数据

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日)。

Image for post
Faker library
法克图书馆

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

现在,安装fakerlodashexpressnodemon npm库

  • faker will be used to generate random mock data

    faker将用于生成随机模拟数据

  • lodash will be used to execute a function for a certain number of times

    lodash将被用于执行功能一定次数

  • express will be used to create REST APIs

    express将用于创建REST API

  • nodemon 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文件现在看起来像这样:

Image for post
package.json
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,

在上面的文件中,

  1. First, we imported all the required packages

    首先,我们导入了所有必需的软件包
  2. 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方法生成例如1​​000条记录,而是使用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访问该应用程序

Image for post
randomly generated list of addresses
随机生成的地址列表

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查询参数,则将出现错误,如下所示。

Image for post
Missing query parameter error
缺少查询参数错误

获取随机产品列表 (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

Image for post
randomly generated list of products
随机生成的产品列表

获取随机图像列表 (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及其相关方法。

Image for post
randomly generated list of images
随机生成的图像列表

获取随机单词列表 (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及其相关方法。

Image for post
randomly generated list of words
随机生成的单词列表

获取随机用户列表 (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及其相关方法。

Image for post
randomly generated list of users
随机生成的用户列表

获取随机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及其相关方法。

Image for post
randomly generated list of lorem ipsum paragraphs
随机生成的lorem ipsum段落列表

获取随机用户信息列表 (Get a List of Random User Information)

Faker library also provides a set of helpers like createCard, userCard, createTransaction.

Faker库还提供了一组帮助器,例如createCarduserCardcreateTransaction

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方法。

Image for post
randomly generated list of user information
随机生成的用户信息列表

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方法。

Image for post
randomly generated list of user information with posts and transactions
随机生成的带有帖子和交易的用户信息列表

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.

今天就这样。 我希望你学到了一些新东西。

翻译自: https://medium.com/javascript-in-plain-english/how-to-generate-mock-data-within-seconds-using-node-js-3add366c4bac

node.js 生成文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值