-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (45 loc) · 1.71 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const fs = require('fs');
const path = require('path');
module.exports = (csvFileName, jsonFileName, callback) => {
if(callback === undefined || typeof callback !== 'function'){
if(csvFileName === undefined || typeof csvFileName === 'function')
throw 'ERROR: You fogot to provide CSV filename.';
if(jsonFileName === undefined || typeof jsonFileName === 'function')
throw 'ERROR: You fogot to provide JSON (output) filename.';
}
// Read the CSV file
fs.readFile(path.join(process.cwd(), csvFileName), 'utf-8', (err, csvData) => {
// Check if there is an error
if (err) return callback(err);
// Split the data by new-line
csvData = csvData.split(/\r\n|\r|\n/g)
// Filter empty values
.filter(data => data !== '')
// And split using commas
.map(data => data.split(','))
// Get headers
const headers = csvData[0];
// convert CSV data to JSON
let jsonData = csvData.splice(1).map(data => {
let temp = {};
data.map((data, item) => {
temp[headers[item]] = data;
});
return temp;
});
// Variable to store JSON
let stringifiedJSON = null;
// JSON.stringify is synchronous => try/catch
try {
stringifiedJSON = JSON.stringify(jsonData, null, 2);
}
catch (err) {
if (err) return callback(err);
}
// Phew! Write everything to file
fs.writeFile(path.join(process.cwd(), jsonFileName), stringifiedJSON, 'utf-8', err => {
if (err) return callback(err);
callback(null);
});
});
};