@types/papaparse

  • Version 5.3.2
  • Published
  • 23.3 kB
  • 1 dependency
  • MIT license

Install

npm i @types/papaparse
yarn add @types/papaparse
pnpm add @types/papaparse

Overview

TypeScript definitions for PapaParse

Index

Variables

variable BAD_DELIMITERS

const BAD_DELIMITERS: readonly string[];
  • An array of characters that are not allowed as delimiters. \r, \n, ", \ufeff

variable DefaultDelimiter

let DefaultDelimiter: string;
  • The delimiter used when it is left unspecified and cannot be detected automatically. Default is comma. ','

variable LocalChunkSize

let LocalChunkSize: number;
  • The size in bytes of each file chunk. Used when streaming files obtained from the DOM that exist on the local computer. Default 10 MB. 10485760

variable NODE_STREAM_INPUT

const NODE_STREAM_INPUT: Symbol;
  • When passed to Papa Parse a Readable stream is returned.

variable RECORD_SEP

const RECORD_SEP: string;
  • The true delimiter. Invisible. ASCII code 30. Should be doing the job we strangely rely upon commas and tabs for.

variable RemoteChunkSize

let RemoteChunkSize: number;
  • Same as LocalChunkSize, but for downloading files from remote locations. Default 5 MB. 5242880

variable UNIT_SEP

const UNIT_SEP: string;
  • Also sometimes used as a delimiting character. ASCII code 31.

variable WORKERS_SUPPORTED

const WORKERS_SUPPORTED: boolean;
  • Whether or not the browser supports HTML5 Web Workers. If false, worker: true will have no effect.

Functions

function parse

parse: {
<T, TFile extends unknown = any>(
file: TFile,
config: ParseLocalConfig<T, TFile>
): void;
<T>(url: string, config: ParseRemoteConfig<T>): void;
<T>(
csvString: string,
config: ParseWorkerConfig<T> & { download?: false }
): void;
<T>(
csvString: string,
config?: ParseConfig<T, undefined> & { download?: false; worker?: false }
): ParseResult<T>;
<T>(
source: any,
config: ParseLocalConfig<T, any> &
(
| (ParseConfig<T, undefined> & { download?: false; worker?: false })
| (ParseWorkerConfig<T> & { download?: false })
| ParseRemoteConfig<T>
)
): void;
(
stream: typeof NODE_STREAM_INPUT,
config?: ParseConfig<any, undefined>
): NodeJS.ReadWriteStream;
};
  • Parse local files

    Parameter file

    a File object obtained from the DOM.

    Parameter config

    a config object which contains a callback.

    Returns

    Doesn't return anything. Results are provided asynchronously to a callback function.

  • Parse remote files

    Parameter url

    the path or URL to the file to download.

    Parameter config

    a config object.

    Returns

    Doesn't return anything. Results are provided asynchronously to a callback function.

  • Parse string in web worker

    Parameter csvString

    a string of delimited text to be parsed.

    Parameter config

    an optional config object.

    Returns

    Doesn't return anything. Results are provided asynchronously to a callback function.

  • Parse string

    Parameter csvString

    a string of delimited text to be parsed.

    Parameter config

    an optional config object.

    Returns

    a parse results object

  • Parse string, remote files or local files

    Parameter source

    data to be parsed.

    Parameter config

    a config object.

    Returns

    Doesn't return anything. Results are provided asynchronously to a callback function.

  • Parse in a node streaming style

    Parameter stream

    NODE_STREAM_INPUT

    Parameter config

    a config object.

    Returns

    a node stream.

    See Also

    • https://github.com/mholt/PapaParse#papa-parse-for-node

function unparse

unparse: <T>(data: T[] | UnparseObject<T>, config?: UnparseConfig) => string;
  • Unparses javascript data objects and returns a csv string

    Parameter data

    can be one of: An array of arrays; An array of objects; An object explicitly defining fields and data

    Parameter config

    an optional config object

Classes

class Parser

class Parser {}
  • On Papa there are actually more classes exposed but none of them are officially documented Since we can interact with the Parser from one of the callbacks I have included the API for this class.

constructor

constructor(config: ParseConfig<any, undefined>);

    method abort

    abort: () => void;

      method getCharIndex

      getCharIndex: () => number;

        method parse

        parse: (input: string, baseIndex: number, ignoreLastRow: boolean) => any;

          method pause

          pause: () => void;

            method resume

            resume: () => void;

              Interfaces

              interface ParseAsyncConfig

              interface ParseAsyncConfig<T = any, TInput = undefined>
              extends ParseConfig<T, TInput> {}

                property chunkSize

                chunkSize?: number | undefined;
                • Overrides Papa.LocalChunkSize and Papa.RemoteChunkSize.

                property worker

                worker?: boolean | undefined;
                • Whether or not to use a worker thread. Using a worker will keep your page reactive, but may be slightly slower. false

                method chunk

                chunk: (results: ParseResult<T>, parser: Parser) => void;
                • A callback function, identical to step, which activates streaming. However, this function is executed after every chunk of the file is loaded and parsed rather than every row. Works only with local and remote files. Do not use both chunk and step callbacks together.

                method complete

                complete: (results: ParseResult<T>, file: TInput) => void;

                method error

                error: (error: Error, file: TInput) => void;
                • A callback to execute if FileReader encounters an error. The function is passed two arguments: the error and the File.

                interface ParseConfig

                interface ParseConfig<T = any, TInput = undefined> {}

                  property comments

                  comments?: false | string | undefined;
                  • A string that indicates a comment (for example, "#" or "//"). When Papa encounters a line starting with this string, it will skip the line. false

                  property delimiter

                  delimiter?: string | ((input: string) => string) | undefined;
                  • The delimiting character. Leave blank to auto-detect from a list of most common delimiters, or any values passed in through delimitersToGuess. It can be a string or a function. If a string, it can be of any length (so multi-character delimiters are supported). If a function, it must accept the input as first parameter and it must return a string which will be used as delimiter. In both cases it cannot be found in Papa.BAD_DELIMITERS. // auto-detect

                  property delimitersToGuess

                  delimitersToGuess?: string[] | undefined;
                  • An array of delimiters to guess from if the delimiter option is not set. [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]

                  property dynamicTyping

                  dynamicTyping?:
                  | boolean
                  | { [headerName: string]: boolean; [columnNumber: number]: boolean }
                  | ((field: string | number) => boolean)
                  | undefined;
                  • If true, numeric and boolean data will be converted to their type instead of remaining strings. Numeric data must conform to the definition of a decimal literal. Numerical values greater than 2^53 or less than -2^53 will not be converted to numbers to preserve precision. European-formatted numbers must have commas and dots swapped. If also accepts an object or a function. If object it's values should be a boolean to indicate if dynamic typing should be applied for each column number (or header name if using headers). If it's a function, it should return a boolean value for each field number (or name if using headers) which will be passed as first argument. false

                  property escapeChar

                  escapeChar?: string | undefined;
                  • The character used to escape the quote character within a field. If not set, this option will default to the value of quoteChar, meaning that the default escaping of quote character within a quoted field is using the quote character two times. (e.g. "column with ""quotes"" in text") '"'

                  property fastMode

                  fastMode?: boolean | undefined;
                  • Fast mode speeds up parsing significantly for large inputs. However, it only works when the input has no quoted fields. Fast mode will automatically be enabled if no " characters appear in the input. You can force fast mode either way by setting it to true or false.

                  property header

                  header?: boolean | undefined;
                  • If true, the first row of parsed data will be interpreted as field names. An array of field names will be returned in meta, and each row of data will be an object of values keyed by field name instead of a simple array. Rows with a different number of fields from the header row will produce an error. Warning: Duplicate field names will overwrite values in previous fields having the same name. false

                  property newline

                  newline?: '\r' | '\n' | '\r\n' | undefined;
                  • The newline sequence. Leave blank to auto-detect. Must be one of \r, \n, or \r\n. // auto-detect

                  property preview

                  preview?: number | undefined;
                  • If > 0, only that many rows will be parsed.

                  property quoteChar

                  quoteChar?: string | undefined;
                  • The character used to quote fields. The quoting of all fields is not mandatory. Any field which is not quoted will correctly read. '"'

                  property skipEmptyLines

                  skipEmptyLines?: boolean | 'greedy' | undefined;
                  • If true, lines that are completely empty (those which evaluate to an empty string) will be skipped. If set to 'greedy', lines that don't have any content (those which have only whitespace after parsing) will also be skipped. false

                  method beforeFirstChunk

                  beforeFirstChunk: (chunk: string) => string | void;
                  • A function to execute before parsing the first chunk. Can be used with chunk or step streaming modes. The function receives as an argument the chunk about to be parsed, and it may return a modified chunk to parse. This is useful for stripping header lines (as long as the header fits in a single chunk).

                  method complete

                  complete: (results: ParseResult<T>, file: TInput) => void;
                  • The callback to execute when parsing is complete. It receives the parse results. If parsing a local file, the File is passed in, too. When streaming, parse results are not available in this callback.

                  method step

                  step: (results: ParseStepResult<T>, parser: Parser) => void;
                  • To stream the input, define a callback function. Streaming is necessary for large files which would otherwise crash the browser. You can call parser.abort() to abort parsing. And, except when using a Web Worker, you can call parser.pause() to pause it, and parser.resume() to resume.

                  method transform

                  transform: (value: string, field: string | number) => any;
                  • A function to apply on each value. The function receives the value as its first argument and the column number or header name when enabled as its second argument. The return value of the function will replace the value it received. The transform function is applied before dynamicTyping.

                  method transformHeader

                  transformHeader: (header: string, index: number) => string;
                  • A function to apply on each header. Requires header to be true. The function receives the header as its first argument and the index as second.

                  interface ParseError

                  interface ParseError {}
                  • Error structure

                  property code

                  code:
                  | 'MissingQuotes'
                  | 'UndetectableDelimiter'
                  | 'TooFewFields'
                  | 'TooManyFields';
                  • Standardized error code

                  property message

                  message: string;
                  • Human-readable details

                  property row

                  row: number;
                  • Row index of parsed data where error is

                  property type

                  type: 'Quotes' | 'Delimiter' | 'FieldMismatch';
                  • A generalization of the error

                  interface ParseLocalConfig

                  interface ParseLocalConfig<T = any, TInput = undefined>
                  extends ParseAsyncConfig<T, TInput> {}

                    property encoding

                    encoding?: string | undefined;
                    • The encoding to use when opening local files. If specified, it must be a value supported by the FileReader API.

                    interface ParseMeta

                    interface ParseMeta {}

                      property aborted

                      aborted: boolean;
                      • Whether process was aborted

                      property cursor

                      cursor: number;

                        property delimiter

                        delimiter: string;
                        • Delimiter used

                        property fields

                        fields?: string[] | undefined;
                        • Array of field names

                        property linebreak

                        linebreak: string;
                        • Line break sequence used

                        property truncated

                        truncated: boolean;
                        • Whether preview consumed all input

                        interface ParseRemoteConfig

                        interface ParseRemoteConfig<T = any> extends ParseAsyncConfig<T, string> {}

                          property download

                          download: true;
                          • This indicates that the string you passed as the first argument to parse() is actually a URL from which to download a file and parse its contents.

                          property downloadRequestBody

                          downloadRequestBody?:
                          | Blob
                          | BufferSource
                          | FormData
                          | URLSearchParams
                          | string
                          | undefined;
                          • Use POST request on the URL of the download option. The value passed will be set as the body of the request. undefined

                          property downloadRequestHeaders

                          downloadRequestHeaders?: { [headerName: string]: string } | undefined;
                          • If defined, should be an object that describes the headers.

                            Example 1

                            { 'Authorization': 'token 123345678901234567890' } undefined

                          property withCredentials

                          withCredentials?: boolean | undefined;
                          • A boolean value passed directly into XMLHttpRequest's "withCredentials" property. undefined

                          interface ParseResult

                          interface ParseResult<T> {}
                          • A parse result always contains three objects: data, errors, and meta. Data and errors are arrays, and meta is an object. In the step callback, the data array will only contain one element.

                          property data

                          data: T[];
                          • an array of rows. If header is false, rows are arrays; otherwise they are objects of data keyed by the field name.

                          property errors

                          errors: ParseError[];
                          • an array of errors.

                          property meta

                          meta: ParseMeta;
                          • contains extra information about the parse, such as delimiter used, the newline sequence, whether the process was aborted, etc. Properties in this object are not guaranteed to exist in all situations.

                          interface ParseStepResult

                          interface ParseStepResult<T> {}
                          • A parse result always contains three objects: data, errors, and meta. Data and errors are arrays, and meta is an object. In the step callback, the data array will only contain one element.

                          property data

                          data: T;
                          • In the step callback, the data array will only contain one element.

                          property errors

                          errors: ParseError[];
                          • an array of errors.

                          property meta

                          meta: ParseMeta;
                          • contains extra information about the parse, such as delimiter used, the newline sequence, whether the process was aborted, etc. Properties in this object are not guaranteed to exist in all situations.

                          interface ParseWorkerConfig

                          interface ParseWorkerConfig<T = any> extends ParseConfig<T> {}

                            property worker

                            worker: true;
                            • Whether or not to use a worker thread. Using a worker will keep your page reactive, but may be slightly slower.

                            method complete

                            complete: (results: ParseResult<T>) => void;
                            • The callback to execute when parsing is complete. It receives the parse results. If parsing a local file, the File is passed in, too. When streaming, parse results are not available in this callback.

                            interface UnparseConfig

                            interface UnparseConfig {}

                              property columns

                              columns?: string[] | undefined;
                              • If data is an array of objects this option can be used to manually specify the keys (columns) you expect in the objects. If not set the keys of the first objects are used as column. undefined

                              property delimiter

                              delimiter?: string | undefined;
                              • The delimiting character. Multi-character delimiters are supported. It must not be found in Papa.BAD_DELIMITERS. ','

                              property escapeChar

                              escapeChar?: string | undefined;
                              • The character used to escape quoteChar inside field values. '"'

                              property escapeFormulae

                              escapeFormulae?: boolean | RegExp | undefined;
                              • If true, field values that begin with =, +, -, or @, will be prepended with a ` to defend against [injection attacks](https://www.contextis.com/en/blog/comma-separated-vulnerabilities), because Excel and LibreOffice will automatically parse such cells as formulae. false

                              property header

                              header?: boolean | undefined;
                              • If false, will omit the header row. If data is an array of arrays this option is ignored. If data is an array of objects the keys of the first object are the header row. If data is an object with the keys fields and data the fields are the header row. true

                              property newline

                              newline?: string | undefined;
                              • The character used to determine newline sequence. '\r\n'

                              property quoteChar

                              quoteChar?: string | undefined;
                              • The character used to quote fields. '"'

                              property quotes

                              quotes?:
                              | boolean
                              | boolean[]
                              | ((value: any, columnIndex: number) => boolean)
                              | undefined;
                              • If true, forces all fields to be enclosed in quotes. If an array of true/false values, specifies which fields should be force-quoted (first boolean is for the first column, second boolean for the second column, ...). A function that returns a boolean values can be used to determine the quotes value of a cell. This function accepts the cell value and column index as parameters. Note that this option is ignored for undefined, null and date-object values. The option escapeFormulae also takes precedence over this.

                                false

                              property skipEmptyLines

                              skipEmptyLines?: boolean | 'greedy' | undefined;
                              • If true, lines that are completely empty (those which evaluate to an empty string) will be skipped. If set to 'greedy', lines that don't have any content (those which have only whitespace after parsing) will also be skipped. false

                              interface UnparseObject

                              interface UnparseObject<T> {}

                                property data

                                data: T[];

                                  property fields

                                  fields: string[];

                                    Type Aliases

                                    type LocalFile

                                    type LocalFile = Blob | NodeJS.ReadableStream;
                                    • File object

                                    Package Files (1)

                                    Dependencies (1)

                                    Dev Dependencies (0)

                                    No dev dependencies.

                                    Peer Dependencies (0)

                                    No peer dependencies.

                                    Badge

                                    To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                    You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@types/papaparse.

                                    • Markdown
                                      [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@types/papaparse)
                                    • HTML
                                      <a href="https://www.jsdocs.io/package/@types/papaparse"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>