UNPKG

@s-hiroshi/bks

Version:

Cli bookmarks application

132 lines 3.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ItemWriter = void 0; /* * @see * https://stackoverflow.com/questions/36856232/write-add-data-in-json-file-using-node-js */ const fs = require('fs'); class ItemWriter { constructor(storageFilePath) { this.storageFilePath = storageFilePath; this.storageFilePage = storageFilePath; this.hasStorage = fs.existsSync(storageFilePath); this.data = null; } /** * create storage file */ create() { let data = { items: [], }; fs.writeFileSync(this.storageFilePage, JSON.stringify(data), { encoding: 'utf8' }, (err) => { if (err) throw err; }); } /** * Read storage file */ read() { this.data = JSON.parse(fs.readFileSync(this.storageFilePage, { encodin: 'utf8' })); } /** * Write storage file */ write() { fs.writeFileSync(this.storageFilePage, JSON.stringify(this.data), { encoding: 'utf8' }, (err) => { if (err) throw err; return true; }); } /** * Append data to storage file * @param item */ append(item) { this.data.items.push(item); this.write(); } /** * Update data in storage file * @param newItem * @param oldItem */ update(newItem, oldItem) { this.data.items = this.data.items.map((item, index) => { if (item.keyword === oldItem.keyword && item.content === oldItem.content) { item.keyword = newItem.keyword; item.content = newItem.content; } return item; }); this.write(); } /** * * @param keyword */ remove(keyword, content) { this.data.items = this.data.items.filter((item) => { if (item.keyword !== keyword || item.content !== content) { return item; } }); this.write(); } /** * Add item * @param item */ add(item) { if (this.hasStorage) { this.read(); this.append(item); } else { this.create(); this.read(); this.append(item); } } /** * Add Items * @param items */ addAll(items) { if (this.hasStorage) { this.read(); items.forEach((item) => { this.append(item); }); } else { this.create(); this.read(); items.forEach((item) => { this.append(item); }); } } /** * Edit item * @param keyword * @param content */ edit(newItem, oldItem) { this.read(); this.update(newItem, oldItem); } /** * Delete item * @param keyword string */ delete(keyword, content) { this.read(); this.remove(keyword, content); } } exports.ItemWriter = ItemWriter; //# sourceMappingURL=ItemWriter.js.map