AWS 提供多语言SDK连接S3存储服务,本文主要描述使用jsSDK连接私有S3节点
const AWS = require('aws-sdk');
AWS.config.update({region: 'eu-west-1'});
var s3 = new AWS.S3({
apiVersion: '2006-03-01', accessKeyId: 'xxxx',
secretAccessKey: 'xxxx',
endpoint: 'https://s3.ap-east-1.amazonaws.com'
});
// test for listbucket
s3.listBuckets(
function (err, data) {
if (err) {
console.log("Error", err);
} else {
let buckets = [];
objs = data.Buckets;
for (let key in objs) {
bucket = objs[key]['Name'];
buckets.push(bucket);
console.log(key + '---' + buckets[key]['Name']);
}
console.log(buckets);
}
}
);
// test for create bucket
let params = {
Bucket: "testbucket"
}
s3.createBucket(params, function (err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("data", data)
}
})
// test for remove bucket
let params = {
Bucket: "testbucket"
}
s3.deleteBucket(params, function (err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("data", data)
}
})
// test for listObjects
let params = {
Bucket: "xxxx",
// MaxKeys: 10
}
s3.listObjects(params, function (err, data) {
if (err) {
console.log("Error", err);
} else {
let objs = [];
let cont = data.Contents;
for (let key in cont) {
obj_name = cont[key].Key;
// console.log(obj_name);
objs.push(obj_name);
}
console.log(objs);
}
})
// test for upload obj
var fs = require("fs");
var fs_data = fs.readFileSync('./test001.txt');
console.log("同步读取: " + fs_data.toString());
params = {
Bucket: "xxxx",
Body: fs_data,
Key: "HappyFace.jpg",
}
s3.upload(params, function (err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("data", data)
}
})
//test for download obj
var fs = require("fs");
let params = {
Bucket: "xxxx",
Key: "xx"//文件名
}
s3.getObject(params, function (err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("data", data.Metadata)
fs.writeFileSync('write.txt', data.Metadata);
}
})