xliff-generator
Version:
A simple module to create xliff files
75 lines (74 loc) • 2.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const csvParse = require("csv-parse");
const csvParseSync = require("csv-parse/lib/sync");
const csv_parse_error_1 = require("../errors/csv-parse.error");
class CsvService {
constructor(logger, fileService) {
this.logger = logger;
this.fileService = fileService;
}
parseCsvSync(config) {
this.logger.trace('Enter CsvService.parseCsvSync(CreateFromCsvConfig)');
try {
const csvFileAsString = this.fileService.readFileSync(config.csvFile).toString('utf8');
let csvValues;
try {
csvValues = csvParseSync(csvFileAsString, {
comment: config.csvComment,
delimiter: config.csvDelimiter,
escape: config.csvEscape,
quote: config.csvQuote,
skip_empty_lines: true
});
}
catch (e) {
this.logger.info('An error occured parse the csv file', e);
throw new csv_parse_error_1.CsvParseError(e);
}
const result = csvValues;
this.checkParsedCsvFile(result);
return result;
}
finally {
this.logger.trace('Leave CsvService.parseCsvSync(CreateFromCsvConfig)');
}
}
parseCsv(config) {
return this.fileService.readFileAsPromise(config.csvFile, 'UTF-8').then((data) => {
return this.parseCsvAsPromise(config, data);
});
}
checkParsedCsvFile(parsedValues) {
if (parsedValues.length === 0) {
throw new csv_parse_error_1.CsvParseError('The csv file contains no parsed csv values. '
+ 'At least the first row with the header has to exist.');
}
}
parseCsvAsPromise(config, csvFileAsString) {
return new Promise((resolve, reject) => {
csvParse(csvFileAsString, {
comment: config.csvComment,
delimiter: config.csvDelimiter,
escape: config.csvEscape,
quote: config.csvQuote,
skip_empty_lines: true
}, (csvErr, csvData) => {
if (csvErr) {
reject(new csv_parse_error_1.CsvParseError(csvErr));
return;
}
const result = csvData;
try {
this.checkParsedCsvFile(result);
}
catch (e) {
reject(new csv_parse_error_1.CsvParseError(e.message));
return;
}
resolve(result);
});
});
}
}
exports.CsvService = CsvService;