UNPKG

10.2 kBTypeScriptView Raw
1// Original definitions in https://github.com/DefinitelyTyped/DefinitelyTyped by: David Muller <https://github.com/davidm77>
2
3/// <reference types="node" />
4
5import * as stream from "stream";
6
7export type Callback = (err: CsvError | undefined, records: any | undefined, info: Info) => void;
8
9export interface Parser extends stream.Transform {}
10
11export class Parser {
12 constructor(options: Options);
13
14 __push(line: any): any;
15
16 __write(chars: any, end: any, callback: any): any;
17
18 readonly options: Options
19
20 readonly info: Info;
21}
22
23export interface CastingContext {
24 readonly column: number | string;
25 readonly empty_lines: number;
26 readonly error: CsvError;
27 readonly header: boolean;
28 readonly index: number;
29 readonly quoting: boolean;
30 readonly lines: number;
31 readonly records: number;
32 readonly invalid_field_length: number;
33}
34
35export type CastingFunction = (value: string, context: CastingContext) => any;
36
37export type CastingDateFunction = (value: string, context: CastingContext) => Date;
38
39export type ColumnOption = string | undefined | null | false | { name: string };
40
41/*
42Note, could not `extends stream.TransformOptions` because encoding can be
43BufferEncoding and undefined as well as null which is not defined in the
44extended type.
45*/
46export interface Options {
47 /**
48 * If true, the parser will attempt to convert read data types to native types.
49 * @deprecated Use {@link cast}
50 */
51 auto_parse?: boolean | CastingFunction;
52 autoParse?: boolean | CastingFunction;
53 /**
54 * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option.
55 * @deprecated Use {@link cast_date}
56 */
57 auto_parse_date?: boolean | CastingDateFunction;
58 autoParseDate?: boolean | CastingDateFunction;
59 /**
60 * If true, detect and exclude the byte order mark (BOM) from the CSV input if present.
61 */
62 bom?: boolean;
63 /**
64 * If true, the parser will attempt to convert input string to native types.
65 * If a function, receive the value as first argument, a context as second argument and return a new value. More information about the context properties is available below.
66 */
67 cast?: boolean | CastingFunction;
68 /**
69 * If true, the parser will attempt to convert input string to dates.
70 * If a function, receive the value as argument and return a new value. It requires the "auto_parse" option. Be careful, it relies on Date.parse.
71 */
72 cast_date?: boolean | CastingDateFunction;
73 castDate?: boolean | CastingDateFunction;
74 /**
75 * List of fields as an array,
76 * a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line,
77 * default to null,
78 * affect the result data set in the sense that records will be objects instead of arrays.
79 */
80 columns?: ColumnOption[] | boolean | ((record: any) => ColumnOption[]);
81 /**
82 * Convert values into an array of values when columns are activated and
83 * when multiple columns of the same name are found.
84 */
85 group_columns_by_name?: boolean;
86 groupColumnsByName?: boolean;
87 /**
88 * Treat all the characters after this one as a comment, default to '' (disabled).
89 */
90 comment?: string;
91 /**
92 * Restrict the definition of comments to a full line. Comment characters
93 * defined in the middle of the line are not interpreted as such. The
94 * option require the activation of comments.
95 */
96 comment_no_infix?: boolean;
97 /**
98 * Set the field delimiter. One character only, defaults to comma.
99 */
100 delimiter?: string | string[] | Buffer;
101 /**
102 * Set the source and destination encoding, a value of `null` returns buffer instead of strings.
103 */
104 encoding?: BufferEncoding | undefined;
105 /**
106 * Set the escape character, one character only, defaults to double quotes.
107 */
108 escape?: string | null | false | Buffer;
109 /**
110 * Start handling records from the requested number of records.
111 */
112 from?: number;
113 /**
114 * Start handling records from the requested line number.
115 */
116 from_line?: number;
117 fromLine?: number;
118 /**
119 * Don't interpret delimiters as such in the last field according to the number of fields calculated from the number of columns, the option require the presence of the `column` option when `true`.
120 */
121 ignore_last_delimiters?: boolean | number;
122 /**
123 * Generate two properties `info` and `record` where `info` is a snapshot of the info object at the time the record was created and `record` is the parsed array or object.
124 */
125 info?: boolean;
126 /**
127 * If true, ignore whitespace immediately following the delimiter (i.e. left-trim all fields), defaults to false.
128 * Does not remove whitespace in a quoted field.
129 */
130 ltrim?: boolean;
131 /**
132 * Maximum numer of characters to be contained in the field and line buffers before an exception is raised,
133 * used to guard against a wrong delimiter or record_delimiter,
134 * default to 128000 characters.
135 */
136 max_record_size?: number;
137 maxRecordSize?: number;
138 /**
139 * Name of header-record title to name objects by.
140 */
141 objname?: string;
142 /**
143 * Alter and filter records by executing a user defined function.
144 */
145 on_record?: (record: any, context: CastingContext) => any;
146 onRecord?: (record: any, context: CastingContext) => any;
147 /**
148 * Optional character surrounding a field, one character only, defaults to double quotes.
149 */
150 quote?: string | boolean | Buffer | null;
151 /**
152 * Generate two properties raw and row where raw is the original CSV row content and row is the parsed array or object.
153 */
154 raw?: boolean;
155 /**
156 * Discard inconsistent columns count, default to false.
157 */
158 relax_column_count?: boolean;
159 relaxColumnCount?: boolean;
160 /**
161 * Discard inconsistent columns count when the record contains less fields than expected, default to false.
162 */
163 relax_column_count_less?: boolean;
164 relaxColumnCountLess?: boolean;
165 /**
166 * Discard inconsistent columns count when the record contains more fields than expected, default to false.
167 */
168 relax_column_count_more?: boolean;
169 relaxColumnCountMore?: boolean;
170 /**
171 * Preserve quotes inside unquoted field.
172 */
173 relax_quotes?: boolean;
174 relaxQuotes?: boolean;
175 /**
176 * One or multiple characters used to delimit record rows; defaults to auto discovery if not provided.
177 * Supported auto discovery method are Linux ("\n"), Apple ("\r") and Windows ("\r\n") row delimiters.
178 */
179 record_delimiter?: string | string[] | Buffer | Buffer[];
180 recordDelimiter?: string | string[] | Buffer | Buffer[];
181 /**
182 * If true, ignore whitespace immediately preceding the delimiter (i.e. right-trim all fields), defaults to false.
183 * Does not remove whitespace in a quoted field.
184 */
185 rtrim?: boolean;
186 /**
187 * Dont generate empty values for empty lines.
188 * Defaults to false
189 */
190 skip_empty_lines?: boolean;
191 skipEmptyLines?: boolean;
192 /**
193 * Skip a line with error found inside and directly go process the next line.
194 */
195 skip_records_with_error?: boolean;
196 skipRecordsWithError?: boolean;
197 /**
198 * Don't generate records for lines containing empty column values (column matching /\s*\/), defaults to false.
199 */
200 skip_records_with_empty_values?: boolean;
201 skipRecordsWithEmptyValues?: boolean;
202 /**
203 * Stop handling records after the requested number of records.
204 */
205 to?: number;
206 /**
207 * Stop handling records after the requested line number.
208 */
209 to_line?: number;
210 toLine?: number;
211 /**
212 * If true, ignore whitespace immediately around the delimiter, defaults to false.
213 * Does not remove whitespace in a quoted field.
214 */
215 trim?: boolean;
216}
217
218export interface Info {
219 /**
220 * Count the number of lines being fully commented.
221 */
222 readonly comment_lines: number;
223 /**
224 * Count the number of processed empty lines.
225 */
226 readonly empty_lines: number;
227 /**
228 * The number of lines encountered in the source dataset, start at 1 for the first line.
229 */
230 readonly lines: number;
231 /**
232 * Count the number of processed records.
233 */
234 readonly records: number;
235 /**
236 * Count of the number of processed bytes.
237 */
238 readonly bytes: number;
239 /**
240 * Number of non uniform records when `relax_column_count` is true.
241 */
242 readonly invalid_field_length: number;
243 /**
244 * Normalized verion of `options.columns` when `options.columns` is true, boolean otherwise.
245 */
246 readonly columns: boolean | { name: string }[] | { disabled: true }[];
247}
248
249export type CsvErrorCode =
250 'CSV_INVALID_OPTION_BOM'
251 | 'CSV_INVALID_OPTION_CAST'
252 | 'CSV_INVALID_OPTION_CAST_DATE'
253 | 'CSV_INVALID_OPTION_COLUMNS'
254 | 'CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME'
255 | 'CSV_INVALID_OPTION_COMMENT'
256 | 'CSV_INVALID_OPTION_DELIMITER'
257 | 'CSV_INVALID_OPTION_ON_RECORD'
258 | 'CSV_INVALID_CLOSING_QUOTE'
259 | 'INVALID_OPENING_QUOTE'
260 | 'CSV_INVALID_COLUMN_MAPPING'
261 | 'CSV_INVALID_ARGUMENT'
262 | 'CSV_INVALID_COLUMN_DEFINITION'
263 | 'CSV_MAX_RECORD_SIZE'
264 | 'CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE'
265 | 'CSV_QUOTE_NOT_CLOSED'
266 | 'CSV_RECORD_INCONSISTENT_FIELDS_LENGTH'
267 | 'CSV_RECORD_INCONSISTENT_COLUMNS'
268 | 'CSV_OPTION_COLUMNS_MISSING_NAME'
269
270export class CsvError extends Error {
271 readonly code: CsvErrorCode;
272 [key: string]: any;
273
274 constructor(code: CsvErrorCode, message: string | string[], options?: Options, ...contexts: any[]);
275}
276
277declare function parse(input: Buffer | string, options?: Options, callback?: Callback): Parser;
278declare function parse(input: Buffer | string, callback?: Callback): Parser;
279declare function parse(options?: Options, callback?: Callback): Parser;
280declare function parse(callback?: Callback): Parser;
281
282// export default parse;
283export { parse }