NodeJS를 사용하여 디렉터리 내의 모든 파일을 S3 버킷에 업로드하려고합니다. Key:
필드에 대한 파일 경로 + 리터럴 문자열을 명시 적으로 제공하면 한 번에 하나의 파일을 업로드 할 수 있습니다 .
다음은 내가 사용중인 스크립트입니다.
var AWS = require('aws-sdk'),
fs = require('fs');
// For dev purposes only
AWS.config.update({ accessKeyId: '...', secretAccessKey: '...' });
// reg ex to match
var re = /\.txt$/;
// ensure that this file is in the directory of the files you want to run the cronjob on
// ensure that this file is in the directory of the files you want to run the cronjob on
fs.readdir(".", function(err, files) {
if (err) {
console.log( "Could not list the directory.", err)
process.exit( 1 )
}
var matches = files.filter( function(text) { return re.test(text) } )
console.log("These are the files you have", matches)
var numFiles = matches.length
if ( numFiles ) {
// Read in the file, convert it to base64, store to S3
for( i = 0; i < numFiles; i++ ) {
var fileName = matches[i]
fs.readFile(fileName, function (err, data) {
if (err) { throw err }
// Buffer Pattern; how to handle buffers; straw, intake/outtake analogy
var base64data = new Buffer(data, 'binary');
var s3 = new AWS.S3()
s3.putObject({
'Bucket': 'noonebetterhaventakenthisbucketnname',
'Key': fileName,
'Body': base64data,
'ACL': 'public-read'
}, function (resp) {
console.log(arguments);
console.log('Successfully uploaded, ', fileName)
})
})
}
}
})
S3에 업로드하려는 각 파일에 대해 다음 오류가 발생합니다.
These are the files you have [ 'test.txt', 'test2.txt' ]
{ '0': null,
'1': { ETag: '"2cad20c19a8eb9bb11a9f76527aec9bc"' } }
Successfully uploaded, test2.txt
{ '0': null,
'1': { ETag: '"2cad20c19a8eb9bb11a9f76527aec9bc"' } }
Successfully uploaded, test2.txt
편집 : 대신 키를 읽을 수 있도록 변수 이름을 사용하여 업데이트matches[i]
업로드 만하는 이유는 무엇 test2.txt
이며 내 matches
변수 내에서 각 파일을 업로드하려면 어떻게해야 합니까?
솔루션에 도달하기 위해 nodejs에서 여러 파일을 비동기 적으로 읽고 캐싱하는 것을 참조했습니다 .
tl; dr 범위 문제-변수를 클로저로 래핑해야합니다. readFile
and에 대한 함수를 만들고 s3.putObject
for 루프 내에서 호출 하여이를 수행 할 수 있습니다 .
var AWS = require('aws-sdk'),
fs = require('fs');
// For dev purposes only
AWS.config.update({ accessKeyId: '...', secretAccessKey: '...' });
var s3 = new AWS.S3()
function read(file) {
fs.readFile(file, function (err, data) {
if (err) { throw err }
// Buffer Pattern; how to handle buffers; straw, intake/outtake analogy
var base64data = new Buffer(data, 'binary');
s3.putObject({
'Bucket': 'noonebetterhaventakenthisbucketnname',
'Key': file,
'Body': base64data,
'ACL': 'public-read'
}, function (resp) {
console.log(arguments);
console.log('Successfully uploaded, ', file)
})
})
}
// reg ex to match
var re = /\.txt$/;
// ensure that this file is in the directory of the files you want to run the cronjob on
fs.readdir(".", function(err, files) {
if (err) {
console.log( "Could not list the directory.", err)
process.exit( 1 )
}
var matches = files.filter( function(text) { return re.test(text) } )
console.log("These are the files you have", matches)
var numFiles = matches.length
if ( numFiles ) {
// Read in the file, convert it to base64, store to S3
for( i = 0; i < numFiles; i++ ) {
read(matches[i])
}
}
})
Эта статья взята из Интернета, укажите источник при перепечатке.
Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.
я говорю два предложения