Skip to content
Open
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.
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
174 changes: 117 additions & 57 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:
## Installation

```sh
npm install vcfTelExtractor
```

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

```
const extractTel = require('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.
## Usage

#### 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.
### Importing the Module

##### Fields and Key Mappings
The following key mappings are utilized to enhance the readability of the output:
**ES Modules (ESM) / TypeScript:**
```typescript
import extractTel, { parseVcard } from 'vcfTelExtractor';

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 import is broken in ESMparseVcard is not a named export (see my note in src/index.ts). Verified it throws SyntaxError: ... does not provide an export named 'parseVcard' at module load. Use import extractTel from 'vcfTelExtractor'; const { parseVcard } = extractTel;, or fix the underlying export.

```

- `TEL` => number
- `FN` => firstName
- `EMAIL` => email
- `VERSION` => version
**CommonJS:**
```javascript
const extractTel = require('vcfTelExtractor');
// The direct string parser is also attached:
// const { parseVcard } = extractTel;
```

### Example Usage
Here is an example demonstrating how to use the extractTel function with the optional parameters:
---

### 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', { fields: ['number', 'firstName'], prefix: true })
.then(data => console.log(data))
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';

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.

🟠 Same broken ESM named import as line 28 — this Example 3 throws a SyntaxError at load for ESM/TS consumers, so the "Browser-Safe" example does not actually run as written. Update it (or fix the export).


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.
87 changes: 0 additions & 87 deletions index.js

This file was deleted.

Loading