Skip to content

Commit

Permalink
feat(stringify): header as comment
Browse files Browse the repository at this point in the history
  • Loading branch information
bluelovers committed Feb 12, 2024
1 parent 28088bc commit ddfeac1
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/csv-stringify/lib/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,9 @@ const stringifier = function(options, state, info){
[err, headers] = this.stringify(headers);
}
if(err) return err;
if(this.options.header_as_comment){
headers = this.options.comment + ' ' + headers;
}
push(headers);
},
__cast: function(value, context){
Expand Down
22 changes: 22 additions & 0 deletions packages/csv-stringify/lib/api/normalize_options.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,28 @@ const normalize_options = function(opts) {
}else{
// todo
}
// Normalize option `headers_as_comment`
if(!options.header_as_comment){
options.header_as_comment = false;
}else if(!options.comment?.length){
throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
'Invalid option comment:',
'comment must be a non empty string or buffer when enable header_as_comment,',
`got ${JSON.stringify(options.comment)}`
], options);
}else{
if(Buffer.isBuffer(options.comment)){
options.comment = options.comment.toString();
}
if(typeof options.comment !== 'string'){
throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
'Invalid option comment:',
'comment must be a buffer or a string when enable header_as_comment,',
`got ${JSON.stringify(options.comment)}`
], options);
}
options.header = true;
}
// Normalize option `columns`
const [errColumns, columns] = normalize_columns(options.columns);
if(errColumns !== undefined) return [errColumns];
Expand Down
8 changes: 8 additions & 0 deletions packages/csv-stringify/lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,14 @@ export interface Options extends stream.TransformOptions {
* Display the column names on the first line if the columns option is provided or discovered.
*/
header?: boolean
/**
* Display the column names on the first line as comment if the columns option is provided or discovered.
*/
header_as_comment?: boolean
/**
* Treat all the characters after this one as a comment, default to '' (disabled).
*/
comment?: string;
/**
* The quote characters, defaults to the ", an empty quote value will preserve the original field.
*/
Expand Down

0 comments on commit ddfeac1

Please sign in to comment.