2017-09-29 5 views
1

인터넷에서이 파일을 사용하여 Amazon S3 서버에 여러 파일을 업로드했습니다.비동기 작업이 완료되면 알림 받기

const AWS = require("aws-sdk"); // from AWS SDK 
    const fs = require("fs"); // from node.js 
    const path = require("path"); // from node.js 

    // configuration 
    const config = { 
     s3BucketName: 'your.s3.bucket.name', 
     folderPath: '../dist' // path relative script's location 
    }; 

    // initialize S3 client 
    const s3 = new AWS.S3({ signatureVersion: 'v4' }); 

    // resolve full folder path 
    const distFolderPath = path.join(__dirname, config.folderPath); 

    // get of list of files from 'dist' directory 
    fs.readdir(distFolderPath, (err, files) => { 

     if(!files || files.length === 0) { 
     console.log(`provided folder '${distFolderPath}' is empty or does not exist.`); 
     console.log('Make sure your project was compiled!'); 
     return; 
     } 

     // for each file in the directory 
     for (const fileName of files) { 

     // get the full path of the file 
     const filePath = path.join(distFolderPath, fileName); 

     // ignore if directory 
     if (fs.lstatSync(filePath).isDirectory()) { 
      continue; 
     } 

     // read file contents 
     fs.readFile(filePath, (error, fileContent) => { 
      // if unable to read file contents, throw exception 
      if (error) { throw error; } 

      // upload file to S3 
      s3.putObject({ 
      Bucket: config.s3BucketName, 
      Key: fileName, 
      Body: fileContent 
      }, (res) => { 
      console.log(`Successfully uploaded '${fileName}'!`); 
      }); 

     }); 
     } 
    }); 

다른 프로세스를 실행하기 위해 업로드가 완료되었음을 어떻게 알릴 수 있습니까? 단일 파일이 성공적으로 업로드되면 res가 호출됩니다.

+0

왜하지 다른 프로세스를 실행하기 위해 알림을 res로 사용 하시겠습니까? – SILENT

+0

새로운 파일이 업로드 될 때마다 res가 호출됩니다. – doej

+1

그래서? 모든 업로드가 완료된 후 질문에 대한 알림이 필요합니까? – SILENT

답변

0

카운터를 증가 할 때 파일 업로드 후 모든 파일이 업로드 된 직접 확인하는 방법 :

... 

var uploadCount = 0 

// Read file contents 
fs.readFile(filePath, (error, fileContent) => { 

    // If unable to read file contents, throw exception 
    if (error) { throw error } 

    // Upload file to S3 
    s3.putObject({ 
    Bucket: config.s3BucketName, 
    Key: fileName, 
    Body: fileContent 
    }, (res) => { 
    console.log(`Successfully uploaded '${fileName}'!`) 

    // Increment counter 
    uploadCount++ 

    // Check if all files have uploaded 
    // 'files' provided in callback from 'fs.readdir()' further up in your code 
    if (uploadCount >= files.length) { 
     console.log('All files uploaded') 
    } 

    }) 

}) 

... 
+0

코드가 누락되었습니다. for 루프에서 multuiple 폴더를 엽니 다. 나는 파일의 수를 모른다. 어떤 해결책이 있습니까? – doej

+0

@doej files.length를 호출 할 때를 알 수 있습니다 ... 또는 for 루프에 카운터를 추가하십시오 – SILENT

0

당신은 약속을 사용하여 시도를 promise.all 수

const AWS = require("aws-sdk"); // from AWS SDK 
const fs = require("fs"); // from node.js 
const path = require("path"); // from node.js 

// configuration 
const config = { 
    s3BucketName: 'your.s3.bucket.name', 
    folderPath: '../dist' // path relative script's location 
}; 

// initialize S3 client 
const s3 = new AWS.S3({ signatureVersion: 'v4' }); 

// resolve full folder path 
const distFolderPath = path.join(__dirname, config.folderPath); 

// get of list of files from 'dist' directory 
fs.readdir(distFolderPath, (err, pathURLS) => { 
    if(!pathURLS || pathURLS.length === 0) { 
    console.log(`provided folder '${distFolderPath}' is empty or does not exist.`); 
    console.log('Make sure your project was compiled!'); 
    return; 
    } 
    let fileUploadPromises = pathURLS.reduce(uplaodOnlyFiles, []); 
    //fileUploadPromises.length should equal the files uploaded 
    Promise.all(fileUploadPromises) 
     .then(() => { 
      console.log('All pass'); 
     }) 
     .catch((err) => { 
      console.error('uploa Failed', err); 
     }); 
}); 

function uploadFileToAWS(filePath) { 
    return new Promise(function (resolve, reject) { 
     try { 
      fs.readFile(filePath, function (err, buffer) { 
       if (err) reject(err); 
       // upload file to S3 
       s3.putObject({ 
        Bucket: config.s3BucketName, 
        Key: filePath, 
        Body: buffer 
       }, (res) => { 
        resolve(res) 
       }); 
      }); 
     } catch (err) { 
      reject(err); 
     } 
    }); 
} 

function uplaodOnlyFiles(fileUploadPromises, pathURL) { 
    const fullPathURL = path.join(distFolderPath, pathURL); 
    if (!fs.lstatSync(fullPathURL).isDirectory()) { 
     fileUploadPromises.push(uploadFileToAWS(fullPathURL)); 
    } 
    return fileUploadPromises; 
} 
관련 문제