JavaScript&TypeScript

JavaScript로 GCS에 파일 업로드 및 다운로드

hjkang 2023. 3. 17. 08:40

Import

const { Storage } = require('@google-cloud/storage')
const xlsx = require('xlsx')

 

GCP Storage에 파일 업로드

try {
  const storage = new Storage()
  await storage
    .bucket(bucket)
    .file(file)
    .save(req.files.image.data, {
      public: false,
   })
} catch (err) {
  console.log('storage error ', err)
}

 

GCP Storage에 업로드한 xlsx 파일을 json으로 조회

const storage = new Storage()
const content = await storage.bucket(bucket).file(path).download()
const workbook = await xlsx.read(content[0], { type: 'buffer' })
const sheetName = workbook.SheetNames[0]
const sheet = workbook.Sheets[sheetName]
const rows = await xlsx.utils.sheet_to_json(sheet, {
	defval: null,
})

console.log(rows)