process-user-img.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import fs from 'fs'
  2. import request from 'request'
  3. import { nanoid } from 'nanoid'
  4. let fileName = './user.json'
  5. let saveFileStr = fs.readFileSync(fileName, 'utf8')
  6. let inputData = JSON.parse(saveFileStr)
  7. const downloadImage = async (src, dest, callback) => {
  8. console.log('下载:', src, dest, Date.now())
  9. return new Promise((resolve) => {
  10. request.head(src, (err) => {
  11. if (err) {
  12. console.log(err)
  13. return
  14. }
  15. src &&
  16. request(src)
  17. .pipe(fs.createWriteStream(dest))
  18. .on('close', () => {
  19. setTimeout(resolve, 1000)
  20. callback && callback(null, dest)
  21. })
  22. })
  23. })
  24. }
  25. let saveFilePath = './user-imgs/'
  26. async function test(list) {
  27. for (let j = 0; j < list.length; j++) {
  28. let a = list[j]
  29. let coverUrl = a.url_list[a.url_list.length - 1]
  30. a.url_list = [coverUrl]
  31. if (coverUrl.includes('http')) {
  32. let name = nanoid() + '.png'
  33. await downloadImage(coverUrl, saveFilePath + name, () => {
  34. // console.log('close', name)
  35. a.url_list = [name]
  36. fs.writeFileSync(fileName, JSON.stringify(inputData, null, 2))
  37. })
  38. }
  39. }
  40. }
  41. async function test2(list) {
  42. for (let j = 0; j < list.length; j++) {
  43. let coverUrl = list[list.length - 1]
  44. if (coverUrl.includes('http')) {
  45. let name = nanoid() + '.png'
  46. await downloadImage(coverUrl, saveFilePath + name, () => {
  47. // console.log('close', name)
  48. fs.writeFileSync(fileName, JSON.stringify(inputData, null, 2))
  49. })
  50. return [name]
  51. }
  52. return []
  53. }
  54. }
  55. for (let i = 0; i < inputData.slice(0, 1111).length; i++) {
  56. let v = inputData[i]
  57. await test(v.cover_url)
  58. await test(v.white_cover_url)
  59. delete v.cover_and_head_image_info
  60. fs.writeFileSync(fileName, JSON.stringify(inputData, null, 2))
  61. if (v.share_info && v.share_info.share_image_url && v.share_info.share_image_url.url_list) {
  62. let r = await test2(v.share_info.share_image_url.url_list)
  63. if (r.length) {
  64. v.share_info.share_image_url.url_list = r
  65. fs.writeFileSync(fileName, JSON.stringify(inputData, null, 2))
  66. }
  67. }
  68. }