Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

iCalendar (ics) file generator for node.js

License

NotificationsYou must be signed in to change notification settings

adamgibbons/ics

Repository files navigation

TheiCalendar generator

npm versionCIDownloads

Install

npm install -S ics

Example Usage

In node / CommonJS

  1. Create an iCalendar event:
constics=require('ics')// or, in ESM: import * as ics from 'ics'constevent={start:[2018,5,30,6,30],duration:{hours:6,minutes:30},title:'Bolder Boulder',description:'Annual 10-kilometer run in Boulder, Colorado',location:'Folsom Field, University of Colorado (finish line)',url:'http://www.bolderboulder.com/',geo:{lat:40.0095,lon:105.2669},categories:['10k races','Memorial Day Weekend','Boulder CO'],status:'CONFIRMED',busyStatus:'BUSY',organizer:{name:'Admin',email:'Race@BolderBOULDER.com'},attendees:[{name:'Adam Gibbons',email:'adam@example.com',rsvp:true,partstat:'ACCEPTED',role:'REQ-PARTICIPANT'},{name:'Brittany Seaton',email:'brittany@example2.org',dir:'https://linkedin.com/in/brittanyseaton',role:'OPT-PARTICIPANT'}]}ics.createEvent(event,(error,value)=>{if(error){console.log(error)return}console.log(value)})// BEGIN:VCALENDAR// VERSION:2.0// CALSCALE:GREGORIAN// PRODID:adamgibbons/ics// METHOD:PUBLISH// X-PUBLISHED-TTL:PT1H// BEGIN:VEVENT// UID:S8h0Vj7mTB74p9vt5pQzJ// SUMMARY:Bolder Boulder// DTSTAMP:20181017T204900Z// DTSTART:20180530T043000Z// DESCRIPTION:Annual 10-kilometer run in Boulder\, Colorado// X-MICROSOFT-CDO-BUSYSTATUS:BUSY// URL:http://www.bolderboulder.com/// GEO:40.0095;105.2669// LOCATION:Folsom Field, University of Colorado (finish line)// STATUS:CONFIRMED// CATEGORIES:10k races,Memorial Day Weekend,Boulder CO// ORGANIZER;CN=Admin:mailto:Race@BolderBOULDER.com// ATTENDEE;RSVP=TRUE;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=Adam Gibbons:mailto:adam@example.com// ATTENDEE;RSVP=FALSE;ROLE=OPT-PARTICIPANT;DIR=https://linkedin.com/in/brittanyseaton;CN=Brittany//   Seaton:mailto:brittany@example2.org// DURATION:PT6H30M// END:VEVENT// END:VCALENDAR
  1. Write an iCalendar file:
const{ writeFileSync}=require('fs')constics=require('ics')ics.createEvent({title:'Dinner',description:'Nightly thing I do',busyStatus:'FREE',start:[2018,1,15,6,30],duration:{minutes:50}},(error,value)=>{if(error){console.log(error)}writeFileSync(`${__dirname}/event.ics`,value)/*You cannot use fs in Frontend libraries like React so you rather import a module to save files to the browser as follow [  import { saveAs } from 'file-saver'; // For saving the file in the browser]const blob = new Blob([value], { type: 'text/calendar' });        saveAs(blob, `${title}.ics`);*/})
  1. Create multiple iCalendar events:
constics=require('./dist')const{ error, value}=ics.createEvents([{title:'Lunch',start:[2018,1,15,12,15],duration:{minutes:45}},{title:'Dinner',start:[2018,1,15,12,15],duration:{hours:1,minutes:30}}])if(error){console.log(error)return}console.log(value)// BEGIN:VCALENDAR// VERSION:2.0// CALSCALE:GREGORIAN// PRODID:adamgibbons/ics// METHOD:PUBLISH// X-PUBLISHED-TTL:PT1H// BEGIN:VEVENT// UID:pP83XzQPo5RlvjDCMIINs// SUMMARY:Lunch// DTSTAMP:20230917T142209Z// DTSTART:20180115T121500Z// DURATION:PT45M// END:VEVENT// BEGIN:VEVENT// UID:gy5vfUVv6wjyBeNkkFmBX// SUMMARY:Dinner// DTSTAMP:20230917T142209Z// DTSTART:20180115T121500Z// DURATION:PT1H30M// END:VEVENT// END:VCALENDAR
  1. Create iCalendar events with Audio (Mac):
letics=require("ics")letmoment=require("moment")letevents=[]letalarms=[]letstart=moment().format('YYYY-M-D-H-m').split("-").map((a)=>parseInt(a))letend=moment().add({'hours':2,"minutes":30}).format("YYYY-M-D-H-m").split("-").map((a)=>parseInt(a))alarms.push({action:'audio',description:'Reminder',trigger:{hours:2,minutes:30,before:true},repeat:2,attachType:'VALUE=URI',attach:'Glass'})letevent={productId:"myCalendarId",uid:"123"+"@ics.com",startOutputType:"local",start:start,end:end,title:"test here",alarms:alarms}events.push(event)console.log(ics.createEvents(events).value)// BEGIN:VCALENDAR// VERSION:2.0// CALSCALE:GREGORIAN// PRODID:myCalendarId// METHOD:PUBLISH// X-PUBLISHED-TTL:PT1H// BEGIN:VEVENT// UID:123@ics.com// SUMMARY:test here// DTSTAMP:20230917T142621Z// DTSTART:20230917T152600// DTEND:20230917T175600// BEGIN:VALARM// ACTION:AUDIO// REPEAT:2// DESCRIPTION:Reminder// ATTACH;VALUE=URI:Glass// TRIGGER:-PT2H30M\nEND:VALARM// END:VEVENT// END:VCALENDAR

Using ESModules & in the browser

import{createEvent}from'ics';constevent={  ...}asyncfunctionhandleDownload(){constfilename='ExampleEvent.ics'constfile=awaitnewPromise((resolve,reject)=>{createEvent(event,(error,value)=>{if(error){reject(error)}resolve(newFile([value],filename,{type:'text/calendar'}))})})consturl=URL.createObjectURL(file);// trying to assign the file URL to a window could cause cross-site// issues so this is a workaround using HTML5constanchor=document.createElement('a');anchor.href=url;anchor.download=filename;document.body.appendChild(anchor);anchor.click();document.body.removeChild(anchor);URL.revokeObjectURL(url);}

API

createEvent(attributes[, callback])

Generates an iCal-compliant VCALENDAR string with one VEVENT.If a callback is not provided, returns an object having the form{ error, value },wherevalue contains an iCal-compliant string if there are no errors.If a callback is provided, returns a Node-style callback.

attributes

Object literal containing event information.Only thestart property is required.

Note all date/time fields can be the array form, or a number representing the unix timestamp in milliseconds (e.g.getTime() on aDate).

The following properties are accepted:

PropertyDescriptionExample
startRequired. Date and time at which the event begins.[2000, 1, 5, 10, 0] (January 5, 2000) or anumber
startInputTypeType of the date/time data instart:
local (default): passed data is in local time.
utc: passed data is UTC
startOutputTypeFormat of the start date/time in the output:
utc (default): the start date will be sent in UTC format.
local: the start date will be sent as "floating" (form #1 inRFC 5545)
endTime at which event ends.Eitherend orduration is required, butnot both.[2000, 1, 5, 13, 5] (January 5, 2000 at 1pm) or anumber
endInputTypeType of the date/time data inend:
local: passed data is in local time.
utc: passed data is UTC.
The default is the value ofstartInputType
endOutputTypeFormat of the start date/time in the output:
utc: the start date will be sent in UTC format.
local: the start date will be sent as "floating" (form #1 inRFC 5545).
The default is the value ofstartOutputType
durationHow long the event lasts. Object literal having form{ weeks, days, hours, minutes, seconds }Eitherend orduration is required, butnot both.{ hours: 1, minutes: 45 } (1 hour and 45 minutes)
titleTitle of event.'Code review'
descriptionDescription of event.'A constructive roasting of those seeking to merge into master branch'
locationIntended venueMountain Sun Pub and Brewery
geoGeographic coordinates (lat/lon){ lat: 38.9072, lon: 77.0369 }
urlURL associated with event'http://www.mountainsunpub.com/'
statusThree statuses are allowed:TENTATIVE,CONFIRMED,CANCELLEDCONFIRMED
organizerPerson organizing the event{ name: 'Adam Gibbons', email: 'adam@example.com', dir: 'https://linkedin.com/in/adamgibbons', sentBy: 'test@example.com' }
attendeesPersons invited to the event[{ name: 'Mo', email: 'mo@foo.com', rsvp: true }, { name: 'Bo', email: 'bo@bar.biz', dir: 'https://twitter.com/bo1234', partstat: 'ACCEPTED', role: 'REQ-PARTICIPANT' }]
categoriesCategories associated with the event['hacknight', 'stout month']
alarmsAlerts that can be set to trigger before, during, or after the event. The followingattach properties work on Mac OS: Basso, Blow, Bottle, Frog, Funk, Glass, Hero, Morse, Ping, Pop, Purr, Sousumi, Submarine, Tink{ action: 'display', description: 'Reminder', trigger: [2000, 1, 4, 18, 30] } OR{ action: 'display', description: 'Reminder', trigger: { hours: 2, minutes: 30, before: true } } OR{ action: 'display', description: 'Reminder', trigger: { hours: 2, minutes: 30, before: false } OR{ action: 'audio', description: 'Reminder', trigger: { hours: 2, minutes: 30, before: true }, repeat: 2, attachType: 'VALUE=URI', attach: 'Glass' }
productIdProduct which created ics,PRODID field'adamgibbons/ics'
uidUniversal unique id for event, produced by default withnanoid.Warning: This value must beglobally unique. It is recommended that it follow theRFC 822 addr-spec (i.e.localpart@domain). Including the@domain half is a good way to ensure uniqueness.'LZfXLFzPPR4NNrgjlWDxn'
methodThis property defines the iCalendar object method associated with the calendar object. When used in a MIME message entity, the value of this property MUST be the same as the Content-Type "method" parameter value. If either the "METHOD" property or the Content-Type "method" parameter is specified, then the other MUST also be specified.PUBLISH
recurrenceRuleA recurrence rule, commonly referred to as an RRULE, defines the repeat pattern or rule for to-dos, journal entries and events. If specified, RRULE can be used to compute the recurrence set (the complete set of recurrence instances in a calendar component). You can use a generator like thisone.FREQ=DAILY
exclusionDatesArray of date-time exceptions for recurring events, to-dos, journal entries, or time zone definitions.[[2000, 1, 5, 10, 0], [2000, 2, 5, 10, 0]] OR[1694941727477, 1694945327477]
sequenceFor sending an update for an event (with the same uid), defines the revision sequence number.2
busyStatusUsed to specify busy status for Microsoft applications, like Outlook. SeeMicrosoft spec.'BUSY' OR'FREE' OR'TENTATIVE' OR'OOF'
transpUsed to specify event transparency (does event consume actual time of an individual). Used by Google Calendar to determine if event should change attendees availability to 'Busy' or not.'TRANSPARENT' OR'OPAQUE'
classificationThis property defines the access classification for a calendar component. SeeiCalender spec.'PUBLIC' OR'PRIVATE' OR'CONFIDENTIAL' OR any non-standard string
createdDate-time representing event's creation date. Provide a date-time in local time[2000, 1, 5, 10, 0] or anumber
lastModifiedDate-time representing date when event was last modified. Provide a date-time in local time[2000, 1, 5, 10, 0] or anumber
calNameSpecifies thecalendar (not event) name. Used by Apple iCal and Microsoft Outlook; seeOpen Specification'Example Calendar'
htmlContentUsed to include HTML markup in an event's description. Standard DESCRIPTION tag should contain non-HTML version.<!DOCTYPE html><html><body><p>This is<br>test<br>html code.</p></body></html>

To create anall-day event, pass only three values (year,month, anddate) to thestart andend properties.The date of theend property should be the dayafter your all-day event.For example, in order to create an all-day event occuring on October 15, 2018:

consteventAttributes={start:[2018,10,15],end:[2018,10,16],/* rest of attributes */}

callback

Optional.Node-style callback.

function(err,value){if(err){// if iCal generation fails, err is an object containing the reason// if iCal generation succeeds, err is null}console.log(value)// iCal-compliant text string}

createEvents(events[, headerParams, callback])

Generates an iCal-compliant VCALENDAR string with multiple VEVENTS.

headerParams may be omitted, and in this case they will be read from the first event.

If a callback is not provided, returns an object having the form{ error, value }, where value is an iCal-compliant text stringiferror isnull.

If a callback is provided, returns a Node-style callback.

events

Array ofattributes objects (as described increateEvent).

callback

Optional.Node-style callback.

function(err,value){if(err){// if iCal generation fails, err is an object containing the reason// if iCal generation succeeds, err is null}console.log(value)// iCal-compliant text string}

Develop

Run mocha tests and watch for changes:

npm start

Run tests once and exit:

npm test

Build the project, compiling all ES6 files within thesrc directory into vanilla JavaScript in thedist directory.

npm run build

References


[8]ページ先頭

©2009-2025 Movatter.jp