【NPM库】- 0x02

时间:2022-07-22
本文章向大家介绍【NPM库】- 0x02,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

目录 1. IP 地址 1.1. internal-ip 1.2. public-ip 1.3. ip 1.4. portfinder 2. URL 解析 2.1. url 2.2. is-absolute-url

1. IP 地址

  • internal-ip:Get your internal IP address。
  • public-ip:Get your public IP address。
const ip = require('internal-ip');
const publicIp = require('public-ip');

(async () => {
    // internalIp
    const iv4 = await ip.v4();
    const iv4Sync = ip.v4.sync();
    console.log(iv4, iv4Sync);

    // publicIp
    const pv4 = await publicIp.v4();
    console.log(pv4);
})();
  • ip:IP address utilities for node.js.
const ip = require('ip');

ip.address() // my ip address
ip.isEqual('::1', '::0:1'); // true
ip.toBuffer('127.0.0.1') // Buffer([127, 0, 0, 1])
ip.toString(new Buffer([127, 0, 0, 1])) // 127.0.0.1
ip.fromPrefixLen(24) // 255.255.255.0
ip.mask('192.168.1.134', '255.255.255.0') // 192.168.1.0
ip.cidr('192.168.1.134/26') // 192.168.1.128
ip.not('255.255.255.0') // 0.0.0.255
ip.or('192.168.1.134', '0.0.0.255') // 192.168.1.255
ip.isPrivate('127.0.0.1') // true
ip.isV4Format('127.0.0.1'); // true
ip.isV6Format('::ffff:127.0.0.1'); // true
  • portfinder:A simple tool to find an open port on the current machine.
const portfinder = require('portfinder');

portfinder.basePort = 9000;    // default: 8000
portfinder.getPortPromise()
    .then((port) => {
        //
        // `port` is guaranteed to be a free port
        // in this scope.
        //
        console.log(port);
    })
    .catch((err) => {
        //
        // Could not get a free port, `err` contains the reason.
        //
        console.error(err);
    });

2. URL 解析

  • url:utilities for URL resolution and parsing.
const url = require('url');

// parse:
const t1 = 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash';
console.log(t1, url.parse(t1));

const t2 = 'http://localhost';
console.log(t2, url.parse(t2));

// format:
console.log(url.format({
    protocol: "http:",
    hostname: "localhost",
    port: 8080
}));
  • is-absolute-url:Check if a URL is absolute
const isAbsoluteUrl = require('is-absolute-url');

const r1 = isAbsoluteUrl('https://sindresorhus.com/foo/bar');
console.log(r1);

const r2 = isAbsoluteUrl('//sindresorhus.com');
console.log(r2);

const r3 = isAbsoluteUrl('foo/bar');
console.log(r3);

参考:

internal-ip: https://github.com/sindresorhus/internal-ip public-ip: https://github.com/sindresorhus/public-ip portfinder: https://github.com/http-party/node-portfinder#readme ip: https://github.com/indutny/node-ip url: https://www.npmjs.com/package/url is-absolute-url: https://github.com/sindresorhus/is-absolute-url