I'm storing key-value pairs as plaintext:
headerlessKey=blahblahblah
{partName}
keyName=value
If I put null
/undefined
as first parameter the key should not have a parent part:
DB.write(null,'headerlessKey','hello world')
DB.write('stuff','someOtherKey',1)
data.tdb:
headerlessKey=hello world
{stuff}
someOtherKey=1
But instead the file looks like:
{stuff}
someOtherKey=1
{null}
headerlessKey=hello world
I want headerlessKey
at top of file contents with no {null}
part. I know:
If I change the value being written while there is still stuff in
data.tdb
the{null}
part appears.Order of operations doesn't matter:
DB.write(null,'headerlessKey','hello world') DB.write('stuff','someOtherKey',1)
Or:
DB.write('stuff','someOtherKey',1) DB.write(null,'headerlessKey','hello world')
{null}
will still appear..tdb file has no {null} part without concurrent
DB.write()
function calls.Issue is likely in
._saveDataToFile()
.
DB.js:
import fs from 'fs';
class DB {
constructor(filePath) {
this.filePath = filePath;
this.data = this._loadDataFromFile();
}
_loadDataFromFile() {
try {
const data = fs.readFileSync(this.filePath, 'utf8');
const entries = data.split(/\r?\n/); // Split by lines
const parsedData = {};
let currentPart = null; // Initialize with null
for (const entry of entries) {
if (entry.startsWith('{')) {
currentPart = entry.slice(1, -1);
parsedData[currentPart] = {};
} else if (entry.includes('=')) {
const [key, value] = entry.split('=');
if (currentPart !== null && key) {
parsedData[currentPart][key] = value;
}
}
}
return parsedData;
} catch (error) {
return {};
}
}
_saveDataToFile() {
let dataStr = '';
for (const part in this.data) {
if (part !== null) {
dataStr += `{${part}}\n`;
for (const key in this.data[part]) {
dataStr += `${key}=${this.data[part][key]}\n`;
}
}
}
if (dataStr.startsWith('{null}\n')) {
dataStr = dataStr.substring('{null}\n'.length);
}
fs.writeFileSync(this.filePath, dataStr, 'utf8');
}
// Public method to read a value
read(partName, keyName) {
if (this.data[partName] && this.data[partName][keyName]) {
return this.data[partName][keyName];
}
return undefined;
}
// Public method to write a value
write(partName, keyName, value) {
if (!this.data[partName]) {
this.data[partName] = {};
}
this.data[partName][keyName] = value;
this._saveDataToFile();
return value;
}
}
export default DB;
I tried a case in the for
loop, but it didn't work. I tried .substring()
and that failed.