This commit is contained in:
Luk 2026-01-21 13:36:42 +08:00
parent 81a47c5f31
commit a415b53549

View File

@ -1,24 +1,36 @@
// 使用Node.js实现Shell脚本逻辑获取公网IP并检查是否以.172结尾 // 使用Node.js实现Shell脚本逻辑获取公网IP并检查是否以.172结尾
const https = require('https') const https = require('https')
https function getEnvByPublicIP () {
.get('https://api.ipify.org', (res) => { return new Promise((resolve, reject) => {
// `curl -s https://ifconfig.me` returns the IP address only, but open the url in browser or with nodejs http module returns the HTML content https
// `https://api.ipify.org` returns the IP address only with curl, browser or nodejs. But it seems it doesn't work in China. .get('https://api.ipify.org', (res) => {
let data = '' let data = ''
res.on('data', (chunk) => (data += chunk)) res.on('data', (chunk) => (data += chunk))
res.on('end', () => { res.on('end', () => {
const ip = data.trim().split(/\s+/)[0] const ip = data.trim().split(/\s+/)[0]
// console.log('public ip:', ip) let result
if (ip.endsWith('.172')) { if (ip.endsWith('.172')) {
console.log('production') result = 'production'
} else if (ip.endsWith('.60')) { } else if (ip.endsWith('.60')) {
console.log('development') result = 'development'
} else { } else {
console.log('development') result = 'development'
} }
}) resolve(result)
}) })
.on('error', (err) => { })
console.error('Request failed:', err) .on('error', (err) => {
reject(err)
})
}) })
}
// 如果直接运行此文件,则执行并打印结果;否则导出函数供其他模块使用
if (require.main === module) {
getEnvByPublicIP()
.then((env) => console.log(env))
.catch((err) => console.error('Request failed:', err))
} else {
module.exports = getEnvByPublicIP
}