Skip to content

Instantly share code, notes, and snippets.

@djom202
Last active June 30, 2023 05:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djom202/93dd6a781cbded543857eaeaa5886b1d to your computer and use it in GitHub Desktop.
Save djom202/93dd6a781cbded543857eaeaa5886b1d to your computer and use it in GitHub Desktop.
This script help to convert some file into the https://pokemonessentials.fandom.com/es/wiki/Archivos_PBS to json
const fs = require('fs');
const path = require('path');
const nReadlines = require('n-readlines');
const source = './src';
function getFiles() {
let arr = [];
const fullPath = path.join(__dirname, source);
const files = fs.readdirSync(fullPath, { withFileTypes: true });
files.forEach((file) => arr.push(file));
return arr;
}
function getDataFromFile(filename) {
const broadbandLines = new nReadlines(filename);
let line;
let lineNumber = 1;
let arr = [];
let obj = {};
while ((line = broadbandLines.next())) {
setLineToObject(line.toString('ascii'), arr, obj);
lineNumber++;
}
arr.push(obj);
return arr;
}
function setLineToObject(line, arr, obj) {
if (line.includes('[') && line.includes(']')) {
const prop = line
.replace('o;?', '')
.replace('[', '')
.replace(']', '')
.replace('\r', '');
if (Object.keys(obj).length > 0) {
arr.push({ ...obj });
}
obj['Id'] = prop;
} else {
const [key, val] = line.replace('\r', '').split('=');
obj[key] = val;
}
}
function saveFile(fullPath, content) {
const newPath =
fullPath.substring(0, fullPath.length - 4).replace('src', 'dist') +
'.json';
try {
const flag = !fs.existsSync(newPath) ? 'a+' : 'w';
writeSave(newPath, content, flag);
} catch (err) {
console.error(err);
}
}
function writeSave(newPath, content, flag) {
fs.writeFileSync(newPath, JSON.stringify(content), {
flag: flag,
});
}
function getExcludeFile() {
return ['.DS_Store'];
}
function convertFile() {
const files = getFiles();
try {
files
.filter((dirent) => dirent.isFile())
.map((filename) => {
if (getExcludeFile().indexOf(filename.name) === -1) {
const fullPath = path.join(
__dirname,
source + '/' + filename.name
);
const data = getDataFromFile(fullPath);
saveFile(fullPath, data);
}
});
} catch (error) {
console.log(error);
}
}
convertFile();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment