diff --git a/packages/csv-stringify/lib/api/index.js b/packages/csv-stringify/lib/api/index.js index 2bd65f6a..a58b2996 100644 --- a/packages/csv-stringify/lib/api/index.js +++ b/packages/csv-stringify/lib/api/index.js @@ -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){ diff --git a/packages/csv-stringify/lib/api/normalize_options.js b/packages/csv-stringify/lib/api/normalize_options.js index 2b92375b..e3f73d31 100644 --- a/packages/csv-stringify/lib/api/normalize_options.js +++ b/packages/csv-stringify/lib/api/normalize_options.js @@ -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]; diff --git a/packages/csv-stringify/lib/index.d.ts b/packages/csv-stringify/lib/index.d.ts index 4c28ef9e..d17007cb 100644 --- a/packages/csv-stringify/lib/index.d.ts +++ b/packages/csv-stringify/lib/index.d.ts @@ -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. */