ical-generator

repository·develop·Indexed 19 days ago

https://github.com/sebbo2002/ical-generator

A lightweight library for creating valid iCal calendar files and subscriptionable calendar feeds. It supports a wide range of date-time types including native JavaScript Date, Day.js, Luxon, moment.js, and Temporal. The library provides comprehensive tools for managing calendar metadata, creating events, configuring alarms with specific trigger types (audio, display, email), and managing attendees with delegation and role settings.

Tokens
10.1K
Snippets
45
Records
51
Agent score
74%

What's inside ical-generator

  1. Supported Date and Time types

    develop

    The library is highly flexible with time inputs. You can provide:

    • Native JavaScript Date objects
    • Day.js objects (requires a plugin for UTC support)
    • Luxon DateTime objects
    • moment.js objects
    • moment-timezone objects
    • TZDate objects
    • Temporal objects
    • Date strings (which are passed to the native Date constructor internally)

    Recommendation: Use UTC time whenever possible. If no timezone is defined, ical-generator outputs all time information as UTC.

  2. Configure Timezones with VTimezone generators

    develop

    When using timezones, it is recommended to use a VTimezone generator to ensure the calendar includes the necessary timezone definitions. You can pass a generator function to the calendar.timezone() method. This function should take a timezone name and return a VTimezone entry.

    Using @touch4it/ical-timezones

    import { ICalCalendar } from 'ical-generator';
    import { getVtimezoneComponent } from '@touch4it/ical-timezones';
    
    const cal = new ICalCalendar();
    cal.timezone({
        name: 'Europe/London',
        generator: getVtimezoneComponent,
    });
    cal.createEvent({
        start: new Date(),
        timezone: 'Europe/London',
    });

    Using timezones-ical-library

    import { ICalCalendar } from 'ical-generator';
    import { tzlib_get_ical_block } from 'timezones-ical-library';
    
    const cal = new ICalCalendar();
    cal.timezone({
        name: 'Europe/Berlin',
        generator: (tz) => tzlib_get_ical_block(tz)[0],
    });
    cal.createEvent({
        start: new Date(),
        timezone: 'Europe/London',
    });
  3. Quick Start: Create an iCal calendar and serve it via HTTP

    develop

    This example demonstrates how to initialize a calendar, set a required method for Outlook compatibility (using ICalCalendarMethod.REQUEST), create an event with specific details, and serve the resulting .ics file using a Node.js HTTP server.

    import ical, { ICalCalendarMethod } from 'ical-generator';
    import http from 'node:http';
    
    const calendar = ical({ name: 'my first iCal' });
    
    // A method is required for outlook to display event as an invitation
    calendar.method(ICalCalendarMethod.REQUEST);
    
    const startTime = new Date();
    const endTime = new Date();
    endTime.setHours(startTime.getHours() + 1);
    calendar.createEvent({
        start: startTime,
        end: endTime,
        summary: 'Example Event',
        description: 'It works ;)',
        location: 'my room',
        url: 'http://sebbo.net/',
    });
    
    http.createServer((req, res) => {
        res.writeHead(200, {
            'Content-Type': 'text/calendar; charset=utf-8',
            'Content-Disposition': 'attachment; filename="calendar.ics",
        });
    
        res.end(calendar.toString());
    }).listen(3000, '127.0.0.1', () => {
        console.log('Server running at http://127.0.0.1:3000/');
    });
  4. Configure Timezones and VTimezone components

    develop

    The timezone method sets the timezone for the calendar. If a timezone is set, ical-generator assumes all provided dates are already in that timezone.

    Using a Timezone Generator

    For best support, you should provide a generator function. This function takes a timezone name (string) and returns a VTimezone component string. This allows the library to automatically include necessary VTIMEZONE entries in the iCal output for all timezones used by the calendar or its events.

    import ical from 'ical-generator';
    import { getVtimezoneComponent } from '@touch4it/ical-timezones';
    
    const cal = ical();
    cal.timezone({
        name: 'FOO',
        generator: getVtimezoneComponent
    });
    
    cal.createEvent({
        start: new Date(),
        timezone: 'Europe/London'
    });
    import ical from 'ical-generator';
    import {getVtimezoneComponent} from '@touch4it/ical-timezones';
    
    const cal = ical();
    cal.timezone({
        name: 'FOO',
        generator: getVtimezoneComponent
    });
    cal.createEvent({
        start: new Date(),
        timezone: 'Europe/London'
    });
  5. Supported date and time types for ICalDateTimeValue

    develop

    The ical-generator library is highly flexible with date handling. When providing date/time values to the API, you can use any of the following:

    • Native JavaScript Date objects.
    • moment.js or moment-timezone objects.
    • day.js objects.
    • luxon DateTime objects.
    • Temporal objects (Instant, PlainDate, PlainDateTime, or ZonedDateTime).
    • ISO strings (which are parsed using the native Date constructor internally).

    This allows you to integrate the generator seamlessly into projects already using specialized date libraries.

  6. Create and use ICalCategory objects

    develop

    An ICalCategory represents a category for an iCalendar event. You can create categories in two ways:

    1. Via an Event instance (Recommended): Use the createCategory() method on an event object created from a calendar.
    2. Directly: Instantiate ICalCategory manually and pass it to an event's categories() method.

    When instantiating manually, you must provide an object containing a name property. If the name is missing or empty, the constructor will throw an error.

    import ical from 'ical-generator';
    
    // Method 1: Via an event
    const calendar = ical();
    const event = calendar.createEvent();
    const category = event.createCategory();
    
    // Method 2: Direct instantiation
    import { ICalCategory } from 'ical-generator';
    const manualCategory = new ICalCategory({ name: 'Work' });
    event.categories([manualCategory]);
  7. Create and use an ICalAlarm

    develop

    You can create an alarm instance in two ways: by calling event.createAlarm() on an existing event, or by instantiating ICalAlarm directly and passing it to event.alarms([...]).

    import ical, { ICalAlarm } from 'ical-generator';
    
    // Method 1: Via event
    const calendar = ical();
    const event = calendar.createEvent();
    const alarm = event.createAlarm();
    
    // Method 2: Directly
    const alarm = new ICalAlarm(alarmData, event);
    event.alarms([alarm]);
    import ical, { ICalAlarm } from 'ical-generator';
    
    // Method 1: Via event
    const calendar = ical();
    const event = calendar.createEvent();
    const alarm = event.createAlarm();
    
    // Method 2: Directly
    const alarm = new ICalAlarm(alarmData, event);
    event.alarms([alarm]);
  8. Initialize an ICalCalendar instance

    develop

    You can create a new calendar instance using the default export or by using the ICalCalendar constructor directly. You can pass an initial configuration object to the constructor or use setter methods to configure the calendar after instantiation.

    import ical from 'ical-generator';
    
    // Method 1: Using the default export (recommended)
    const cal = ical({ name: 'my first iCal' });
    
    // Method 2: Using the constructor directly
    import { ICalCalendar } from 'ical-generator';
    const cal = new ICalCalendar();
    
    // Method 3: Chaining setters
    const cal = ical().name('my first iCal');
    
    // Method 4: Manual setters
    const cal = ical();
    cal.name('sebbo.net');
    import ical from 'ical-generator';
    const cal = ical({name: 'my first iCal'});
  9. Serialize ICalCategory to JSON

    develop

    To persist or serialize a category, use the toJSON() method. It returns a shallow copy of the category's internal data (an object containing the name property), which is suitable for JSON.stringify().

    const category = new ICalCategory({ name: 'Urgent' });
    const json = JSON.stringify(category.toJSON());
    // Result: '{"name":"Urgent"}'
  10. Repeat alarms with intervals

    develop

    You can make an alarm repeat by providing a repeat object containing times (number of repetitions) and interval (duration between repetitions in seconds).

    // repeat the alarm 4 times every 5 minutes (300 seconds)
    const alarm = event.createAlarm({
        repeat: {
            times: 4,
            interval: 300
        }
    });
    // repeat the alarm 4 times every 5 minutes (300 seconds)
    const alarm = event.createAlarm({
        repeat: {
            times: 4,
            interval: 300
        }
    });
  11. Manage calendar events

    develop

    You can add events to a calendar using createEvent for single events or events for bulk addition.

    Adding Events

    • createEvent(data: ICalEvent | ICalEventData): Creates a new ICalEvent and adds it to the calendar. Returns the created event instance.
    • events(events?: (ICalEvent | ICalEventData)[]): If provided with an array, it adds multiple events to the calendar. If called without arguments, it returns the array of all current ICalEvent objects.
    • clear(): Removes all events from the calendar without affecting other metadata.
    • length(): Returns the number of events currently in the calendar.
    const cal = ical();
    
    // Create a single event
    const event = cal.createEvent({ summary: 'My Event' });
    event.summary('Your Event');
    
    // Add multiple events at once
    cal.events([
        {
           start: new Date(),
           end: new Date(new Date().getTime() + 3600000),
           summary: 'Example Event',
           description: 'It works ;)',
           url: 'http://sebbo.net/'
        }
    ]);
    
    // Get all events
    const allEvents = cal.events();