UNPKG

@giorgi-g/csv-parser

Version:

CSV parser for migrations with Sequelizer

53 lines (52 loc) 2.46 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.File = void 0; const fs = require("fs"); class File { constructor(filePath, extension = 'txt', encoding = 'utf8', jsonReplacer = null, jsonSpacer = 2, plainFile = false) { this.filePath = ''; this.extension = 'txt'; this.encoding = 'utf8'; this.jsonReplacer = null; this.plainFile = false; this.read = () => __awaiter(this, void 0, void 0, function* () { try { if (this.plainFile) { return fs.readFileSync(`${this.filePath}.${this.extension}`, this.encoding); } return JSON.parse(fs.readFileSync(`${this.filePath}.${this.extension}`, this.encoding)); } catch (err) { return []; } }); this.clear = () => __awaiter(this, void 0, void 0, function* () { return yield this.write([]); }); this.write = (data) => __awaiter(this, void 0, void 0, function* () { const path = `${this.filePath}.${this.extension}`; const stream = this.plainFile && typeof data === 'string' ? data : JSON.stringify(data, this.jsonReplacer, this.jsonSpacer); return fs.writeFile(path, stream, (err) => { if (err) return console.log(err); console.log(`Writing files inside ${this.filePath}.${this.extension} finished!`); }); }); this.filePath = filePath; this.extension = extension; this.encoding = encoding; this.jsonReplacer = jsonReplacer; this.jsonSpacer = jsonSpacer; this.plainFile = plainFile; } } exports.File = File;