-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (84 loc) · 2.24 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* read lines by file path
*/
const debug = require("debug")("readlineq");
const fs = require("fs");
/**
* read file into lines
* @param {[type]} file_path [description]
* @return {[type]} [description]
*/
function _read(file_path) {
var lines = [];
return new Promise((resolve, reject) => {
var lineReader = require("readline").createInterface({
input: require("fs").createReadStream(file_path),
});
lineReader.on("line", function (line) {
debug("Line from file: %s", line);
lines.push(line);
});
lineReader.on("close", function (err) {
debug("all lines are read, line size %d", lines.length);
resolve(lines);
});
lineReader.on("error", function (err) {
debug("error happens", err);
reject(err);
});
});
}
// const JSONStream = require('JSONStream');
/**
* Dump huge array to file
* @param {*} to dump obj to file path
* @param {*} obj JSONObject or JSONArray
*/
// function _write(to, obj) {
// return new Promise((resolve, reject) => {
// var records = obj
// var transformStream = JSONStream.stringify();
// var outputStream = fs.createWriteStream(to);
// transformStream.pipe(outputStream);
// records.forEach(transformStream.write);
// transformStream.end();
// outputStream.on(
// "finish",
// function handleFinish() {
// resolve();
// }
// );
// outputStream.on(
// "error",
// function handleFinish(err) {
// reject(err);
// }
// );
// });
// }
//
/**
* Write lines to file
* @param {[type]} from_ [description]
* @param {[type]} to_ [description]
* @return {[type]} [description]
*/
function _write(lines, to_) {
if (typeof lines === "string") {
fs.writeFileSync(to_, lines);
} else if (lines.length > 0) {
fs.writeFileSync(to_, lines.join(""));
}
}
/**
* write or read data
* @param {[type]} file_path [description]
* @param {[type]} obj [description]
* @return {[type]} [description]
*/
exports = module.exports = function (file_path, obj) {
if (obj) {
return _write(obj, file_path);
}
return _read(file_path);
};