写个jsdelivr上传Github文件代码
时间: 2024-01-21 18:43:18 浏览: 143
使用git上传代码到github
4星 · 用户满意度95%
以下是一个示例代码,可以将文件上传到 GitHub,并使用 jsDelivr 提供的 CDN 服务。
```javascript
const fetch = require('node-fetch');
const owner = 'your_github_username';
const repo = 'your_github_repository_name';
const token = 'your_github_personal_access_token';
// Upload file to GitHub
async function uploadToGitHub(filePath, content) {
const url = `https://api.github.com/repos/${owner}/${repo}/contents/${filePath}`;
const body = {
message: 'Add file via API',
content: Buffer.from(content).toString('base64')
};
const headers = {
Authorization: `Bearer ${token}`
};
const response = await fetch(url, {
method: 'PUT',
headers,
body: JSON.stringify(body)
});
const json = await response.json();
if (response.ok) {
console.log(`File uploaded to GitHub: ${json.content.html_url}`);
return json.content.sha;
} else {
console.error(`Failed to upload file to GitHub: ${JSON.stringify(json)}`);
return null;
}
}
// Get jsDelivr upload URL
async function getJsDelivrUrl(filePath, sha) {
const url = `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${sha}/${filePath}`;
const response = await fetch(url);
const json = await response.json();
if (response.ok && json.success) {
console.log(`jsDelivr upload URL: ${json.files[0].url}`);
return json.files[0].url;
} else {
console.error(`Failed to get jsDelivr upload URL: ${JSON.stringify(json)}`);
return null;
}
}
// Upload file to jsDelivr
async function uploadToJsDelivr(filePath, content) {
const sha = await uploadToGitHub(filePath, content);
if (sha) {
const url = await getJsDelivrUrl(filePath, sha);
if (url) {
const response = await fetch(url, {
method: 'PUT',
body: content
});
if (response.ok) {
console.log(`File uploaded to jsDelivr: ${url}`);
} else {
console.error(`Failed to upload file to jsDelivr: ${response.statusText}`);
}
}
}
}
// Example usage
uploadToJsDelivr('example.txt', 'Hello, world!');
```
在使用此代码之前,请确保您已经设置了 GitHub 个人访问令牌,并具有对您要上传文件的仓库的写入访问权限。您还应该替换代码中的 `your_github_username`,`your_github_repository_name` 和 `your_github_personal_access_token` 为您自己的值。
阅读全文