rsnext/packages/create-next-app/helpers/is-online.ts
Ivan Torres 13f7ad3204
Add protocol node: imports (#66813)
I have added to all packages that are imported from node, the `node:`
and I have reordered the imports, first the `node:` ones to make it more
readable, as well as only importing the necessary functions.

I ran a `node --prof` before and after the modifications and it seems to
be more optimal now than before.

Co-authored-by: torresgol10.itd <torresgol10.itd@gmail.com>
Co-authored-by: Sam Ko <sam@vercel.com>
2024-06-17 00:31:10 -07:00

45 lines
1.1 KiB
TypeScript

import { execSync } from 'node:child_process'
import { lookup } from 'node:dns/promises'
import url from 'node:url'
function getProxy(): string | undefined {
if (process.env.https_proxy) {
return process.env.https_proxy
}
try {
const httpsProxy = execSync('npm config get https-proxy').toString().trim()
return httpsProxy !== 'null' ? httpsProxy : undefined
} catch (e) {
return
}
}
export async function getOnline(): Promise<boolean> {
try {
await lookup('registry.yarnpkg.com')
// If DNS lookup succeeds, we are online
return true
} catch {
// The DNS lookup failed, but we are still fine as long as a proxy has been set
const proxy = getProxy()
if (!proxy) {
return false
}
const { hostname } = url.parse(proxy)
if (!hostname) {
// Invalid proxy URL
return false
}
try {
await lookup(hostname)
// If DNS lookup succeeds for the proxy server, we are online
return true
} catch {
// The DNS lookup for the proxy server also failed, so we are offline
return false
}
}
}