From a415b53549541adaf6a8b7a0ee71d0549aac8b67 Mon Sep 17 00:00:00 2001 From: Luk Date: Wed, 21 Jan 2026 13:36:42 +0800 Subject: [PATCH] u --- prod_or_dev.js | 52 +++++++++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/prod_or_dev.js b/prod_or_dev.js index 1636a5d..6a2a633 100644 --- a/prod_or_dev.js +++ b/prod_or_dev.js @@ -1,24 +1,36 @@ // 使用Node.js实现Shell脚本逻辑:获取公网IP并检查是否以.172结尾 const https = require('https') -https - .get('https://api.ipify.org', (res) => { - // `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://api.ipify.org` returns the IP address only with curl, browser or nodejs. But it seems it doesn't work in China. - let data = '' - res.on('data', (chunk) => (data += chunk)) - res.on('end', () => { - const ip = data.trim().split(/\s+/)[0] - // console.log('public ip:', ip) - if (ip.endsWith('.172')) { - console.log('production') - } else if (ip.endsWith('.60')) { - console.log('development') - } else { - console.log('development') - } - }) - }) - .on('error', (err) => { - console.error('Request failed:', err) +function getEnvByPublicIP () { + return new Promise((resolve, reject) => { + https + .get('https://api.ipify.org', (res) => { + let data = '' + res.on('data', (chunk) => (data += chunk)) + res.on('end', () => { + const ip = data.trim().split(/\s+/)[0] + let result + if (ip.endsWith('.172')) { + result = 'production' + } else if (ip.endsWith('.60')) { + result = 'development' + } else { + result = 'development' + } + resolve(result) + }) + }) + .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 +}