95 lines
2.5 KiB
JavaScript
95 lines
2.5 KiB
JavaScript
/**
|
|
* Upload public/assets (and optional public/audio) to Aliyun OSS.
|
|
*
|
|
* Target layout (matches VITE_OSS_BASE + /assets/...):
|
|
* oss://{bucket}/dukang_office/assets/...
|
|
* oss://{bucket}/dukang_office/audio/...
|
|
*
|
|
* Required env:
|
|
* OSS_REGION e.g. oss-cn-hangzhou
|
|
* OSS_BUCKET e.g. dukang-prod
|
|
* OSS_ACCESS_KEY_ID
|
|
* OSS_ACCESS_KEY_SECRET
|
|
* Optional:
|
|
* OSS_PREFIX default dukang_office
|
|
* OSS_ENDPOINT custom endpoint if needed
|
|
*/
|
|
import fs from 'node:fs/promises'
|
|
import path from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import OSS from 'ali-oss'
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
const root = path.resolve(__dirname, '..')
|
|
|
|
const region = process.env.OSS_REGION
|
|
const bucket = process.env.OSS_BUCKET
|
|
const accessKeyId = process.env.OSS_ACCESS_KEY_ID
|
|
const accessKeySecret = process.env.OSS_ACCESS_KEY_SECRET
|
|
const prefix = (process.env.OSS_PREFIX || 'dukang_office').replace(/^\/|\/$/g, '')
|
|
const endpoint = process.env.OSS_ENDPOINT
|
|
|
|
if (!region || !bucket || !accessKeyId || !accessKeySecret) {
|
|
console.error(
|
|
'Missing OSS env. Set OSS_REGION, OSS_BUCKET, OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET',
|
|
)
|
|
process.exit(1)
|
|
}
|
|
|
|
const client = new OSS({
|
|
region,
|
|
bucket,
|
|
accessKeyId,
|
|
accessKeySecret,
|
|
...(endpoint ? { endpoint } : {}),
|
|
})
|
|
|
|
async function walk(dir) {
|
|
const entries = await fs.readdir(dir, { withFileTypes: true })
|
|
const files = []
|
|
for (const entry of entries) {
|
|
const full = path.join(dir, entry.name)
|
|
if (entry.isDirectory()) {
|
|
files.push(...(await walk(full)))
|
|
} else {
|
|
files.push(full)
|
|
}
|
|
}
|
|
return files
|
|
}
|
|
|
|
async function uploadDir(localDir, remoteSubdir) {
|
|
try {
|
|
await fs.access(localDir)
|
|
} catch {
|
|
console.warn(`skip (missing): ${localDir}`)
|
|
return 0
|
|
}
|
|
|
|
const files = await walk(localDir)
|
|
let count = 0
|
|
for (const file of files) {
|
|
const rel = path.relative(localDir, file).split(path.sep).join('/')
|
|
const key = `${prefix}/${remoteSubdir}/${rel}`
|
|
await client.put(key, file, {
|
|
headers: {
|
|
'Cache-Control': 'public, max-age=2592000',
|
|
},
|
|
})
|
|
count += 1
|
|
console.log(`put ${key}`)
|
|
}
|
|
return count
|
|
}
|
|
|
|
async function main() {
|
|
const n1 = await uploadDir(path.join(root, 'public/assets'), 'assets')
|
|
const n2 = await uploadDir(path.join(root, 'public/audio'), 'audio')
|
|
console.log(`\nDone. uploaded ${n1 + n2} files under oss://${bucket}/${prefix}/`)
|
|
}
|
|
|
|
main().catch((err) => {
|
|
console.error(err)
|
|
process.exit(1)
|
|
})
|