Introduction to node-ical
node-ical is a powerful library that allows you to parse and process iCalendar (.ics) files in Node.js. Whether you’re building a calendar application or just need to read event data, node-ical provides a robust API to get the job done.
Installation
npm install node-ical
APIs and Usage
Parsing an iCalendar File
const ical = require('node-ical');
const data = ical.parseFile('path/to/your/calendar.ics');
console.log(data);
Fetching Calendar Events from a URL
const ical = require('node-ical');
ical.fromURL('http://example.com/calendar.ics', {}, (err, data) => {
if (err) throw err;
console.log(data);
});
Listing Events with Details
const ical = require('node-ical');
ical.fromURL('http://example.com/calendar.ics', {}, (err, data) => {
if (err) throw err;
for (let k in data) {
if (data.hasOwnProperty(k)) {
const event = data[k];
if (event.type === 'VEVENT') {
console.log(`Event: ${event.summary}, Start: ${event.start}, End: ${event.end}`);
}
}
}
});
Filtering Events by Date
const ical = require('node-ical');
const events = ical.sync.parseFile('path/to/your/calendar.ics');
const filteredEvents = Object.values(events).filter((event) => {
return event.type === 'VEVENT' && event.start >= new Date();
});
console.log(filteredEvents);
Application Example
Let’s build a small Node.js application that uses node-ical to fetch and display upcoming events from a public calendar URL.
const express = require('express');
const ical = require('node-ical');
const app = express();
app.get('/events', (req, res) => {
ical.fromURL('http://example.com/public-calendar.ics', {}, (err, data) => {
if (err) {
res.status(500).send('Error fetching calendar');
return;
}
const events = Object.values(data).filter(event => event.type === 'VEVENT');
res.json(events);
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
With this application, you can fetch and display events by visiting http://localhost:3000/events
.
Hash: 207ef7c12ca6b59ee4f2c179cf67eb543f679676a8879fb949ab954b4b70dc48