process-xhs-img.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import fs from 'fs'
  2. import request from 'request'
  3. import { nanoid } from 'nanoid'
  4. let fileName = './xhs.json'
  5. let savefileName = './xhs-save.json'
  6. let saveFileStr = fs.readFileSync(fileName, 'utf8')
  7. let inputData = JSON.parse(saveFileStr)
  8. const downloadImage = async (src, dest, callback) => {
  9. console.log('下载:', src, dest, Date.now())
  10. return new Promise((resolve) => {
  11. request.head(src, (err) => {
  12. if (err) {
  13. console.log(err)
  14. return
  15. }
  16. src &&
  17. request(src)
  18. .pipe(fs.createWriteStream(dest))
  19. .on('close', () => {
  20. setTimeout(resolve, 1500)
  21. callback && callback(null, dest)
  22. })
  23. })
  24. })
  25. }
  26. let saveFilePath = './imgs/'
  27. let imgList = []
  28. async function test(list) {
  29. for (let j = 0; j < list.length; j++) {
  30. let a = list[j]
  31. let coverUrl = a.info_list[0].url
  32. let rIndex = imgList.findIndex((v) => v.url === coverUrl)
  33. if (rIndex === -1) {
  34. if (coverUrl.includes('http')) {
  35. let name = nanoid() + '.png'
  36. imgList.push({
  37. name,
  38. url: coverUrl
  39. })
  40. await downloadImage(coverUrl, saveFilePath + name, () => {
  41. // console.log('close', name)
  42. list[j] = {
  43. info_list: [
  44. {
  45. url: name
  46. }
  47. ]
  48. }
  49. fs.writeFileSync(savefileName, JSON.stringify(inputData, null, 2))
  50. })
  51. }
  52. } else {
  53. list[j] = {
  54. info_list: [
  55. {
  56. url: imgList[rIndex].name
  57. }
  58. ]
  59. }
  60. console.log('重复')
  61. fs.writeFileSync(savefileName, JSON.stringify(inputData, null, 2))
  62. }
  63. }
  64. }
  65. for (let i = 0; i < inputData.slice(0, 111111).length; i++) {
  66. let v = inputData[i]
  67. if (v.note_card?.cover) {
  68. let url = v.note_card?.cover?.url_default
  69. let name = nanoid() + '.png'
  70. imgList.push({
  71. name,
  72. url: url
  73. })
  74. await downloadImage(url, saveFilePath + name, () => {
  75. // console.log('close', name)
  76. v.note_card.cover = { url_default: name }
  77. fs.writeFileSync(savefileName, JSON.stringify(inputData, null, 2))
  78. })
  79. }
  80. if (v.note_card?.image_list) {
  81. await test(v.note_card.image_list)
  82. }
  83. }