is-reachable 项目使用教程

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 函数接受两个参数:hostsoptions
    • hosts 可以是一个字符串或一个字符串数组,表示要检查的 URL。
    • options 是一个对象,包含了超时时间等配置。
  • 该函数使用 got 库进行 HTTP 请求,使用 dns.lookup 进行 DNS 查询,通过 p-anyp-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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

解卿靓Fletcher

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值