Last active
July 12, 2019 20:56
-
-
Save PeterPorzuczek/319702f133786414d06a6e17ca67ae75 to your computer and use it in GitHub Desktop.
Edit JSON file and save output | Alternative with Imgur image reupload
This file contains hidden or 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 fs = require('fs'); | |
| function storeData(data, pathWithName) { | |
| fs.writeFileSync(`${pathWithName}.json`, JSON.stringify(data)); | |
| return data; | |
| } | |
| function readData(pathWithName) { | |
| var data = fs.readFileSync(`${pathWithName}.json`); | |
| return JSON.parse(data); | |
| } | |
| function changeElement(element, iteration) { | |
| element.id = iteration; | |
| return element; | |
| } | |
| function changeElements(elements) { | |
| let _elements = []; | |
| _elements = elements.map((element, iteration) => changeElement(element, iteration)); | |
| return _elements; | |
| } | |
| const data = readData('./someJsonFile'); | |
| data.elements = changeElements(data.elements); | |
| const newData = storeData(data, './newJsonFile'); |
This file contains hidden or 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 fs = require('fs'); | |
| const imgur = require("imgur"); | |
| const sleep = require('util').promisify(setTimeout) | |
| const delay = 1000; | |
| function storeData(data, pathWithName) { | |
| fs.writeFileSync(`${pathWithName}.json`, JSON.stringify(data)); | |
| return data; | |
| } | |
| function readData(pathWithName) { | |
| var data = fs.readFileSync(`${pathWithName}.json`); | |
| return JSON.parse(data); | |
| } | |
| async function changeElement(element, iteration) { | |
| try { | |
| await sleep(delay * iteration); | |
| const { | |
| data | |
| } = await imgur.uploadUrl(encodeURI(element.pictureUrl)); | |
| element.pictureUrl = data.link; | |
| } catch (err) { | |
| console.log(err); | |
| } | |
| return element; | |
| } | |
| async function changeElements(elements) { | |
| let _elements = []; | |
| const promises = await elements.map(async (element, iteration) => await changeElement(element, iteration)); | |
| _elements = await Promise.all(promises) | |
| return _elements; | |
| } | |
| async function run() { | |
| const data = readData('./someJsonFile'); | |
| data.elements = await changeElements(data.elements); | |
| const newData = storeData(data, './newJsonFile'); | |
| } | |
| run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment