Last active
December 20, 2023 05:40
-
-
Save SiZapPaaiGwat/f604966ad89dd0c589905f15d6129c2e to your computer and use it in GitHub Desktop.
upload-next-static-to-r2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// eslint-disable-next-line | |
const fs = require('node:fs/promises') | |
// eslint-disable-next-line | |
const path = require('node:path') | |
// eslint-disable-next-line | |
const { glob } = require('glob') | |
// eslint-disable-next-line | |
const Promise = require('bluebird') | |
// eslint-disable-next-line | |
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3') | |
// eslint-disable-next-line | |
const { lookup } = require('mime-types') | |
const website = require('./configs/website.json') | |
const ACCOUNT_ID = process.env.R2_ACCOUNT_ID | |
const ACCESS_KEY_ID = process.env.R2_ACCESS_KEY_ID | |
const SECRET_ACCESS_KEY = process.env.R2_SECRET_ACCESS_KEY | |
// 移除首字符的 / | |
const outStaticDir = '.next/static' | |
const s3 = new S3Client({ | |
region: 'auto', | |
endpoint: `https://${ACCOUNT_ID}.r2.cloudflarestorage.com`, | |
credentials: { | |
accessKeyId: ACCESS_KEY_ID, | |
secretAccessKey: SECRET_ACCESS_KEY | |
} | |
}) | |
const cwd = process.cwd() | |
async function uploadFiles(s3BucketName, pattern) { | |
if (!s3BucketName) { | |
throw new Error('s3BucketName is required') | |
} | |
const files = await glob(pattern) | |
await Promise.map( | |
files, | |
async (file) => { | |
let key = website.cdn_dir + '/' + file.replace(cwd + '/', '') | |
key = key.startsWith('/') ? key.slice(1) : key | |
const params = { | |
Bucket: s3BucketName, | |
ContentType: lookup(key), | |
// cache for a year | |
CacheControl: 'public, max-age=31536000', | |
Key: key.replace('/.next/', '/_next/'), | |
Body: await fs.readFile(file) | |
} | |
await s3.send(new PutObjectCommand(params)) | |
console.log(`Uploaded ${key}`) | |
}, | |
{ concurrency: 10 } | |
) | |
} | |
uploadFiles(process.env.R2_BUCKET, `${cwd}/${outStaticDir}/**/*.*`).catch((err) => { | |
console.log(err) | |
process.exit(1) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment