Skip to content

Instantly share code, notes, and snippets.

@scarlac
Last active January 12, 2023 19:51
Show Gist options
  • Save scarlac/dac371d54f1335d779821c214387d7ca to your computer and use it in GitHub Desktop.
Save scarlac/dac371d54f1335d779821c214387d7ca to your computer and use it in GitHub Desktop.
Redux Persist script that convert the double-encoded persisted reducer state files into normal JSON files
/* eslint-disable no-console */
const fs = require('fs');
const path = require('path');
/**
* Redux Persist script that convert the double-encoded persisted reducer state files into normal JSON files.
* Usage: node convert-persist-state-to-json.js /tmp/Documents/persistStore
* generates several files:
* persistStore/persist-root -> persistStore/persist-root.json
* persistStore/persist-user -> persistStore/persist-user.json
* ...
* A macOS Shortcuts shortcut can be set up so you can right click to convert a file or folder directly from Finder:
* -----
* [ -> Receive [Files and Folders] input from [Quick Actions] ]
* [ If there's no input: [Stop and Respond] ]
* -----
* [ Repeat with each item in [Shortcut Input (File/File)] ]
* -----
* [ Run Shell Script ]
* [ ``` ]
* [ cd /Users/myuser/scripts/ ]
* [ node convert-persist-state-to-json.js [File Path (File/File Path)] ]
* [ ``` ]
* [ Shell: [zsh] ]
* [ Input: [Shortcut Input (File/File Path)] ]
* [ Pass Input: [to stdin] ]
* [ Run as Administrator: [ ] ]
*/
const inputFolderOrFiles = process.argv[2];
if (!inputFolderOrFiles) {
console.log('Usage: node convert-persist-state-to-json.js /tmp/Documents/persistStore');
console.log('Usage: node convert-persist-state-to-json.js /tmp/Documents/persistStore/persist-user');
process.exit(1);
}
const files = [];
for (let i = 2; i < process.argv.length; i++) {
const arg = process.argv[i];
if (fs.statSync(arg).isDirectory()) {
console.log(`Reading from ${arg} folder`);
const filesInDir = fs.readdirSync(arg).filter(
f => f.startsWith('persist-') && !f.endsWith('.json')
);
files.push(...filesInDir.map(f => path.join(arg, f)));
} else {
// files separated by one or more whitespaces
files.push(arg);
}
}
for (const inPath of files) {
const inFilename = path.basename(inPath);
const outFilename = `${inFilename}.json`;
const outPath = path.join(path.dirname(inPath), outFilename);
console.log(`Converting ${inFilename} to ${outFilename}`);
const rawObj = JSON.parse(fs.readFileSync(inPath));
const parsedObj = {};
for (const prop in rawObj) {
if (typeof rawObj[prop] === 'string') {
parsedObj[prop] = JSON.parse(rawObj[prop]);
} else {
parsedObj[prop] = rawObj[prop];
}
}
fs.writeFileSync(outPath, JSON.stringify(parsedObj, null, 2), { encoding: 'utf8' });
}
console.log('Done');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment