is-reachable 项目使用教程
is-reachableCheck if servers are reachable项目地址:https://gitcode.com/gh_mirrors/is/is-reachable
1. 项目的目录结构及介绍
is-reachable 是一个用于检查 URL 是否可达的 Node.js 模块。以下是该项目的目录结构:
is-reachable/
├── index.js
├── license
├── package.json
├── readme.md
└── test/
├── fixture.js
├── index.js
└── node-fetch.js
目录结构介绍
index.js
: 项目的主文件,包含了检查 URL 是否可达的逻辑。license
: 项目的许可证文件。package.json
: 项目的配置文件,包含了项目的依赖、脚本等信息。readme.md
: 项目的说明文档。test/
: 项目的测试目录,包含了多个测试文件。fixture.js
: 测试用的辅助文件。index.js
: 主要的测试文件。node-fetch.js
: 使用node-fetch
进行测试的文件。
2. 项目的启动文件介绍
项目的启动文件是 index.js
,该文件导出了一个异步函数 isReachable
,用于检查给定的 URL 是否可达。以下是 index.js
的部分代码:
const dns = require('dns');
const got = require('got');
const pAny = require('p-any');
const pTimeout = require('p-timeout');
const defaults = {
timeout: 5000,
queryOptions: {}
};
const isReachable = (hosts, options) => {
options = { ...defaults, ...options };
if (typeof hosts === 'string') {
hosts = [hosts];
}
const check = host => {
return pAny([
() => got(host, { retry: 0, timeout: options.timeout }).then(() => true).catch(() => false),
() => new Promise((resolve, reject) => {
dns.lookup(host, options.queryOptions, err => {
resolve(!err);
});
})
]);
};
return pTimeout(pAny(hosts.map(check)), options.timeout);
};
module.exports = isReachable;
启动文件介绍
isReachable
函数接受两个参数:hosts
和options
。hosts
可以是一个字符串或一个字符串数组,表示要检查的 URL。options
是一个对象,包含了超时时间等配置。
- 该函数使用
got
库进行 HTTP 请求,使用dns.lookup
进行 DNS 查询,通过p-any
和p-timeout
库进行异步处理。
3. 项目的配置文件介绍
项目的配置文件是 package.json
,该文件包含了项目的元数据、依赖、脚本等信息。以下是 package.json
的部分内容:
{
"name": "is-reachable",
"version": "4.0.0",
"description": "Check if a local or remote URL is reachable",
"license": "MIT",
"repository": "sindresorhus/is-reachable",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"reachable",
"url",
"website",
"http",
"network",
"dns",
"reachable",
"check",
"is",
"detect",
"internet",
"online",
"offline"
],
"dependencies": {
"got": "^11.0.2",
"p-any": "^3.0.0",
"p-timeout": "^3.1.0"
},
"devDependencies": {
"ava": "^3.11.1",
"
is-reachableCheck if servers are reachable项目地址:https://gitcode.com/gh_mirrors/is/is-reachable