Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed .DS_Store
Binary file not shown.
24 changes: 24 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: CI

on:
push:
branches: [master]
pull_request:

jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node-version: ['18.x', '20.x']
steps:
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- run: npm ci
- run: npm run build
- run: npm test
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
node_modules
node_modules
dist
.DS_Store
54 changes: 54 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Changelog

All notable changes to this project are documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [2.0.0] - 2026-07-14

Full rewrite in TypeScript with a spec-compliant vCard parser. This is a major
release with breaking changes — see **Migrating from 1.x** below.

### Added
- Direct parsing of raw vCard **string** content via both `extractTel(string)`
and the new synchronous, browser-safe `parseVcard(string, options?)` export.
- **Isomorphic** support: a dedicated browser entry point (`dist/browser`) that
never touches `fs`, plus a Node entry point that reads files or strings.
- **Dual package**: ESM (`import`) and CommonJS (`require()`) with generated
type declarations (`.d.ts`).
- RFC 6350 **line unfolding**, **unescaping** (`\n`, `\,`, `\;`, `\\`), and
correct colon handling so values containing `:` (e.g. URLs) parse intact.
- Optional **phone-number normalization** to E.164 via `libphonenumber-js`
(`normalize: true`, with an optional `countryCode`), plus a custom
`normalize` callback.
- **Multi-value fields**: repeated properties collect into arrays by default
(`multiValueMode: 'array'`), or keep only the last value (`'last'`).
- Custom key **`mappings`** to rename/extend the default field mapping.
- Opt-in property **parameters** metadata via `params: true`
(e.g. `TEL;TYPE=CELL` → `params: { number: [{ TYPE: ['CELL'] }] }`).

### Changed
- **BREAKING**: minimum supported Node.js is now `>=18.0.0`.
- **BREAKING**: `onlyNumbers` now derives numbers from parsed `TEL` fields
(structured) instead of a whole-file regex scan; output strings are stripped
of spaces/hyphens.
- Package entry points now resolve to compiled output in `dist/`.

### Fixed
- Correct single-pass unescaping (no double-processing of `\\`).

### Migrating from 1.x
- Requires Node.js 18+.
- Default output for repeated fields is now an **array**; pass
`multiValueMode: 'last'` to restore 1.x single-value behaviour.
- `extractTel` still accepts a file path in Node, but now also accepts raw
vCard string content.

## [1.0.0] - 2023-09-30

- Initial published release: extract telephone numbers and selected fields
from a vCard file path.

[2.0.0]: https://github.com/Balanced02/vcfTelExtractor/compare/v1.0.0...v2.0.0
[1.0.0]: https://github.com/Balanced02/vcfTelExtractor/releases/tag/v1.0.0
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2012 Wouter Vroege
Copyright (c) 2026 Balanced02 (Adepoju Daniel)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
178 changes: 119 additions & 59 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,86 +1,146 @@
# vcfTelExtractor

`vcfTelExtractor` is a node.js module designed to extract telephone numbers along with other specified fields from vCard (.vcf) files. The module is highly customizable allowing users to specify output fields and format, making it a versatile solution for any project requiring parsing vCard files.
`vcfTelExtractor` is a robust, lightweight, and spec-compliant vCard (.vcf) parser for Node.js and the browser. Written in TypeScript, it supports dual CommonJS/ESM modules, correct line unfolding, and phone number normalization via `libphonenumber-js`.

## Installation
## Features
* **Isomorphic:** Runs seamlessly in both Node.js (reading from files or strings) and browser environments (reading from strings).
* **Dual package:** Support for both ESM `import` and CommonJS `require()`.
* **RFC Spec Compliant:** Correctly handles vCard line unfolding, unescaping, and parameter/group attributes.
* **Phone Normalization:** Clean and format numbers using `libphonenumber-js` (e.g., converting local numbers to E.164 format).
* **Multi-Value Fields:** Handles contacts with multiple phone numbers or emails by default (converting to arrays), with optional backward compatibility.

To install the `vcfTelExtractor` module, use the following npm command:
---

```sh
npm install vcfTelExtractor
```

# Usage
## Importing the Module
To import the vcfTelExtractor module, require it in your file as shown below:
## Installation

```
const extractTel = require('vcfTelExtractor');
```sh
npm install vcftelextractor
```

### extractTel Function
`extractTel` function is the core of this module. It parses the vCard files and extracts the required information based on the provided options.
---

#### Parameters
- path (String): The path to the vCard file. This is a required parameter.
- options (Object): An optional parameter object containing the following properties:
- fields (Array): Defines the keys that should be present in the output. If not provided, all available fields will be included.
- onlyNumbers (Boolean): When true, the function returns only an array of telephone numbers. Default is false.
- prefix (Boolean): When true, the extracted telephone numbers will include the prefix. Default is false.
## Usage

##### Fields and Key Mappings
The following key mappings are utilized to enhance the readability of the output:
### Importing the Module

- `TEL` => number
- `FN` => firstName
- `EMAIL` => email
- `VERSION` => version

### Example Usage
Here is an example demonstrating how to use the extractTel function with the optional parameters:
**ES Modules (ESM) / TypeScript:**
```typescript
import extractTel, { parseVcard } from 'vcftelextractor';
```

**CommonJS:**
```javascript
const extractTel = require('vcftelextractor');
// The direct string parser is also attached:
// const { parseVcard } = extractTel;
```
extractTel('./contacts.vcf', { fields: ['number', 'firstName'], prefix: true })
.then(data => console.log(data))

---

### API Guide

#### `extractTel(input, options?)`
Core function. In Node.js, it accepts a file path or a raw vCard string. In the browser, it accepts a raw vCard string. Returns a `Promise`.

* **`input` (String):** The path to the vCard file (Node.js only) or raw vCard string content.
* **`options` (Object):** Optional configuration object:
* **`fields` (Array<String>):** List of mapped fields to include in the output. If empty, all available fields are included.
* **`onlyNumbers` (Boolean):** If `true`, returns a flat array of phone number strings (spaces/hyphens stripped). Default is `false`.
* **`prefix` (Boolean):** If `true`, includes the `+` prefix for phone numbers in `onlyNumbers` output. Default is `false`.
* **`normalize` (Boolean | Function):** Normalization strategy:
* `true`: Normalizes numbers to E.164 format using `libphonenumber-js`.
* `false` (default): Cleans formatting (replaces hyphens/spaces with a space) for backward compatibility.
* `Function`: Custom callback `(phone: string) => string`.
* **`countryCode` (String):** Default country code (e.g., `'US'`, `'GB'`) to use for national phone numbers when `normalize: true`.
* **`mappings` (Object):** Custom key mappings to extend or override default mappings. Default mappings:
* `TEL` => `number`
* `FN` => `firstName`
* `EMAIL` => `email`
* `VERSION` => `version`
* **`multiValueMode` (String):** Action for fields appearing multiple times per contact:
* `'array'` (default): Combines values into an array (e.g., `number: ['+123', '+456']`).
* `'last'`: Overwrites with the last value (v1 behavior).
* **`params` (Boolean):** If `true`, includes parameter attributes (like `TYPE=CELL`) in a nested metadata `params` property for each contact. Default is `false`.

#### `parseVcard(vcardString, options?)`
A synchronous, browser-safe function that parses a raw vCard string content directly.

---

### Examples

#### Example 1: Basic Node.js File Extraction
```javascript
const extractTel = require('vcftelextractor');

extractTel('./contacts.vcf')
.then(contacts => console.log(contacts))
.catch(err => console.error(err));
```

### Testing
`vcfTelExtractor` comes with extensive test cases, providing coverage for a variety of scenarios and edge cases. To run the tests, execute the following command:
#### Example 2: Normalizing Phone Numbers (ESM)
```typescript
import extractTel from 'vcftelextractor';

const result = await extractTel('./contacts.vcf', {
normalize: true,
countryCode: 'US', // Parse US local format numbers like (650) 555-0100
});
console.log(result);
// Output phone numbers will be normalized to E.164: '+16505550100'
```
npm test

#### Example 3: Direct String Parsing (Browser-Safe)
```javascript
import { parseVcard } from 'vcftelextractor';

const rawVcard = `BEGIN:VCARD
VERSION:3.0
FN:Jane Doe
TEL;TYPE=CELL:+15555555555
END:VCARD`;

const contacts = parseVcard(rawVcard, { fields: ['firstName', 'number'] });
console.log(contacts);
// [{ firstName: 'Jane Doe', number: '+15555555555' }]

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This documented output is now inaccurate — because the input uses TEL;TYPE=CELL, the actual result also includes params: { number: [{ TYPE: ['CELL'] }] } (see my note in src/parser.ts). Either update the expected output here or make params opt-in.

```

### Errors and Exception Handling
This module is designed to handle errors gracefully by rejecting the promise returned by the extractTel function. Users should implement appropriate error handling in their applications.
#### Example 4: Extracting Parameters and Attributes
```javascript
import { parseVcard } from 'vcftelextractor';

const rawVcard = `BEGIN:VCARD
VERSION:3.0
FN:Jane Doe
TEL;TYPE=CELL,VOICE;VALUE=uri:+15555555555
END:VCARD`;

const contacts = parseVcard(rawVcard, { params: true });
console.log(contacts);
/* Output:
[{
firstName: 'Jane Doe',
number: '+15555555555',
version: '3.0',
params: {
number: [{ TYPE: ['CELL', 'VOICE'], VALUE: ['uri'] }]
}
}]
*/
```

### Contribution
We welcome and appreciate contributions to enhance vcfTelExtractor. Please ensure any contributed code is accompanied by relevant tests.
---

### License
## Testing

(The MIT License)
To run the unit tests:

Copyright (c) 2012 Wouter Vroege
```sh
npm test
```

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
---

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
## License

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
MIT License. Copyright (c) 2012 Wouter Vroege, 2026 Balanced02.
Loading
Loading