counter8
Version:
Counter8 allows you to create and update counters directly from the command line or other Node.js scripts.
58 lines (51 loc) • 1.71 kB
JavaScript
const fs = require("fs").promises;
const lockfile = require("proper-lockfile");
class Counter {
constructor(name) {
this.name = name;
this.path = `./${name}.txt`;
}
async add(value) {
try {
const release = await lockfile.lock(this.path);
const currentValue = parseInt(await fs.readFile(this.path, "utf8"));
// Convert value to a number before performing the addition
const numvalue = Number(value)
const newValue = currentValue + numvalue;
await fs.writeFile(this.path, newValue.toString(), "utf8");
release(); // Release the lock
console.log(`Counter ${this.name} updated to ${newValue}.`);
} catch (error) {
console.error(
`Failed to update counter ${this.name}: ${error.message}`,
);
throw error;
}
}
static async new(name) {
const counter = new Counter(name);
try {
await fs.access(counter.path);
console.log(`Counter ${name} already exists.`);
return counter;
} catch (error) {
if (error.code === "ENOENT") {
await fs.writeFile(counter.path, "0", { flag: "wx" });
console.log(`Counter ${name} created successfully.`);
return counter;
} else {
console.error(`Failed to access counter ${name}: ${error.message}`);
throw error;
}
}
}
async get(name) {
try {
const nameCounter = new Counter(name); // Use 'new' keyword to create a new instance
return nameCounter;
} catch (err) {
console.error(`Failed to get counter ${name}: ${err.message}`);
}
}
}
module.exports = Counter;