-
-
Save soomtong/3b58bf09ca26a99e660dc2cf4587bf47 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path'); | |
const fs = require('fs'); | |
const crypto = require('crypto'); | |
const { promisify } = require('util'); | |
const readdirAsync = promisify(fs.readdir); | |
const statAsync = promisify(fs.stat); | |
const imageSizeAsync = promisify(imageSize); | |
const asyncForEach = async (array, callback) => { | |
for (let index = 0; index < array.length; index += 1) { | |
await callback(array[index], index, array); | |
} | |
}; | |
async function getFiles(dir) { | |
const subdirs = await readdirAsync(dir); | |
const files = await Promise.all( | |
subdirs.map(async subdir => { | |
const res = path.resolve(dir, subdir); | |
return (await statAsync(res)).isDirectory() ? getFiles(res) : res; | |
}) | |
); | |
return files.reduce((a, f) => a.concat(f), []); | |
} | |
const main = async () => { | |
const BASE_URL = 'http://static.fastcampus.co.kr/assets'; | |
const baseDir = path.resolve(__dirname, '../html/assets'); | |
try { | |
let insertCount = 0; | |
let updateCount = 0; | |
const files = await getFiles(baseDir); | |
await asyncForEach(files, async (file, index) => { | |
const code = file.substring(baseDir.length + 1); | |
const mimeType = mime.lookup(code) || 'application/octet-stream'; | |
if (/^image\//.test(mimeType)) { | |
const dim = await imageSizeAsync(file); | |
imageWidth = dim.width; | |
imageHeight = dim.height; | |
} | |
const existing = await Asset.selectByCode(code); | |
if (existing) { | |
updateCount += 1; | |
await Asset.updateById(existing.id, Object.assign(existing, asset)); | |
} else { | |
insertCount += 1; | |
await Asset.insert({ | |
type: 'ASSET', | |
state: 'NORMAL', | |
}); | |
} | |
}); | |
} catch (e) { | |
error('failed to upsert assets', e); | |
} | |
}; | |
main().catch(err => { | |
error(err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment