get images from rss feed and post as json in typescript

To get images from an RSS feed and post them as JSON in TypeScript, we can use the following steps:

  1. Install axios and xml2js packages.
index.ts
npm install axios xml2js
25 chars
2 lines
  1. Import the required libraries and set up axios to fetch the RSS feed.
index.ts
import axios from 'axios';
import { parseStringPromise } from 'xml2js';
const rssUrl = 'https://example.com/feed.xml';
const response = await axios.get(rssUrl)
160 chars
5 lines
  1. Parse the RSS feed using xml2js package and extract the images.
index.ts
const parsedResult = await parseStringPromise(response.data);
const items = parsedResult['rss']['channel'][0]['item'];

const imageUrls = items.map(item => {
  const content = item['content:encoded'][0];
  const regex = /<img.+?src="(.+?)"/;
  const match = regex.exec(content);
  return match ? match[1] : '';
});
315 chars
10 lines
  1. Convert the extracted image URLs to JSON format and post them to an API endpoint.
index.ts
const imagesJson = JSON.stringify(imageUrls);
const endpointUrl = 'https://api.example.com/image-uploads';
const response = await axios.post(endpointUrl, imagesJson);
167 chars
4 lines

Putting it all together, the TypeScript code should look like this:

index.ts
import axios from 'axios';
import { parseStringPromise } from 'xml2js';

const rssUrl = 'https://example.com/feed.xml';
const endpointUrl = 'https://api.example.com/image-uploads';

const extractImagesFromRss = async () => {
  try {
    const response = await axios.get(rssUrl);
    const parsedResult = await parseStringPromise(response.data);
    const items = parsedResult['rss']['channel'][0]['item'];

    const imageUrls = items.map(item => {
      const content = item['content:encoded'][0];
      const regex = /<img.+?src="(.+?)"/;
      const match = regex.exec(content);
      return match ? match[1] : '';
    });

    const imagesJson = JSON.stringify(imageUrls);
    await axios.post(endpointUrl, imagesJson);
  } catch (error) {
    console.error(error);
  }
}

extractImagesFromRss();
801 chars
28 lines

gistlibby LogSnag