Skip to main content
numpy-ts provides NumPy-compatible text parsing and serialization, split into environment-agnostic browser functions and Node.js file I/O functions.

Browser API

These functions work with strings and can be used in any JavaScript environment.

parseTxt

Parse a text string into an NDArray. Each row must have the same number of values.
function parseTxt(text: string, options?: ParseTxtOptions): NDArray
NameTypeDefaultDescription
textstringThe text content to parse.
optionsParseTxtOptions{}Parsing options (see table below).
Returns: NDArray — 2-D array (or 1-D if a single row/column).
import { parseTxt } from 'numpy-ts';

const csv = `1,2,3
4,5,6
7,8,9`;

const arr = parseTxt(csv, { delimiter: ',' });
// shape [3, 3]

serializeTxt

Serialize an NDArray to a text string.
function serializeTxt(arr: NDArray, options?: SerializeTxtOptions): string
NameTypeDefaultDescription
arrNDArrayArray to serialize (must be 1-D or 2-D).
optionsSerializeTxtOptions{}Serialization options (see table below).
Returns: string — Text representation of the array.
import * as np from 'numpy-ts';
import { serializeTxt } from 'numpy-ts';

const arr = np.array([[1, 2, 3], [4, 5, 6]]);
const csv = serializeTxt(arr, { delimiter: ',', fmt: '%d' });
// "1,2,3\n4,5,6\n"

genfromtxt

Parse a text file with more flexible handling of missing values. Replaces missing values with a fill value instead of throwing.
function genfromtxt(path: string, options?: LoadTxtOptions): Promise<NDArray>
NameTypeDefaultDescription
pathstringPath to the text file to parse.
optionsLoadTxtOptions{}Parsing options. Use missing_values and filling_values to handle gaps.
Returns: NDArray — Parsed array with missing values filled in.
import { genfromtxt } from 'numpy-ts/node';

const arr = await genfromtxt('data.csv', {
  delimiter: ',',
  missing_values: [''],
  filling_values: 0,
});
// array([[1, 2, 3],
//        [4, 0, 6],
//        [7, 8, 0]])

fromregex

Extract data from a text file using a regular expression with capture groups.
function fromregex(path: string, regexp: RegExp | string, dtype?: DType): Promise<NDArray>
NameTypeDefaultDescription
pathstringPath to the text file to search.
regexpRegExp | stringRegular expression with capture groups. Each match produces one row; each group produces one column.
dtypeDType'float64'Data type of the resulting array.
Returns: NDArray — Array with one row per match and one column per capture group.
import { fromregex } from 'numpy-ts/node';

const arr = await fromregex('points.log', /x=([\d.]+), y=([\d.]+)/);
// array([[1.5, 2.3],
//        [3.0, 4.1],
//        [5.5, 6.7]])

Options Reference

ParseTxtOptions

NameTypeDefaultDescription
delimiterstringwhitespaceString used to separate values. By default, any consecutive whitespace acts as delimiter.
commentsstring'#'Character indicating the start of a comment line.
skiprowsnumber0Number of lines to skip at the beginning of the file.
usecolsnumber | number[]allWhich columns to read (0-indexed).
max_rowsnumberallMaximum number of data rows to read (after skiprows).
dtypeDType'float64'Data type of the resulting array.
encodingstring'utf-8'Character encoding (only relevant for Node.js file operations).
missing_valuesstring | string[]undefinedString representation(s) of missing values (used by genfromtxt).
filling_valuesnumberNaN (float) / 0 (int)Replacement value for missing entries.

SerializeTxtOptions

NameTypeDefaultDescription
fmtstring'%.18e'Printf-style format string. Examples: '%.6f' (6 decimals), '%.2e' (scientific), '%d' (integer).
delimiterstring' 'String separating columns.
newlinestring'\n'String written at the end of each row.
headerstringundefinedText written at the beginning of the file. Automatically prefixed with the comment character.
footerstringundefinedText written at the end of the file.
commentsstring'# 'String prepended to header and footer lines.

Node.js API

loadtxt

Load data from a text file on disk.
function loadtxt(path: string, options?: LoadTxtOptions): Promise<NDArray>
NameTypeDefaultDescription
pathstringPath to the text file.
optionsLoadTxtOptions{}Parsing options.
Returns: Promise<NDArray> — The parsed array.
import * as np from 'numpy-ts/node';

// Load CSV
const data = await np.loadtxt('data.csv', { delimiter: ',' });

// Load with column selection and header skip
const subset = await np.loadtxt('data.txt', {
  usecols: [0, 2],
  skiprows: 1,
});

savetxt

Save an array to a text file.
function savetxt(
  path: string,
  arr: NDArray,
  options?: SaveTxtOptions
): Promise<void>
NameTypeDefaultDescription
pathstringOutput file path.
arrNDArrayArray to save (must be 1-D or 2-D).
optionsSaveTxtOptions{}Serialization options.
Returns: Promise<void>
import * as np from 'numpy-ts/node';

const arr = np.array([[1, 2, 3], [4, 5, 6]]);

// Save as CSV
await np.savetxt('output.csv', arr, { delimiter: ',', fmt: '%d' });

// Save with header
await np.savetxt('output.txt', arr, {
  header: 'x y z',
  fmt: '%.4f',
});