Harrison Cramer
Harrison Cramer

Reputation: 4496

Writing Multiple Files From Node.js Stream

I'm writing a short Node.js snippet that parses an RSS feed, extracts the links, reconfigures them to the PDF links that I want, and then writes those files. The code looks like this:

var https = require('https');
var fs = require('fs');
const Parser = require("rss-parser");
let parser = new Parser();

parser.parseURL("https://regulations.justia.com/regulations/fedreg?limit=20&mode=atom")
  .then((feed) => {
    const base = "https://docs.regulations.justia.com/entries"
    feed.items.forEach((item, i) => {

      // Parsing to create PDF link...
      const str = item.link;
      let dates = str.substring(50, 60);
      let newDates = dates.replace(/\//, "-").replace(/\//, "-");
      let ending = str.substring(61).replace(".html",".pdf");
      let fullString = `${base}/${newDates}/${ending}`;

      // Fetching and saving the PDF file....
      const file = fs.createWriteStream(`${item.title}.pdf`);
      const request = https.get(fullString, (res) => {
        res.pipe(file);
      });
    });
  })
  .catch((err) => console.log(err));

I'm experiencing two errors right now.

1) Something to do with my writeable stream. When I try to create the file based on the item.title from the RSS feed, I get this error every time:

Error: ENOENT: no such file or directory, open 'Notice - Solicitation of Nominations for Appointment to the World Trade Center Health Program Scientific/Technical Advisory Committee (STAC).pdf'

Does this have something to do with either the parentheses or the em-dash in the item title? If not, what else could be causing this issue?

2) When I do change the code (to name the writeable stream to something more simple) my code will throw the following error:

Error: socket hang up
    at TLSSocket.onHangUp (_tls_wrap.js:1135:19)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:111:20)
    at TLSSocket.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1056:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

This error is thrown usually after I've downloaded a number of the PDFs, but not all. What can I change in this example to get past these errors? Thank for your help!

Upvotes: 0

Views: 1316

Answers (1)

Matus Dubrava
Matus Dubrava

Reputation: 14462

The problem is that the some of item.title's contain / character which indicates a folder that does not exist in this case.

It works when you get rid of those / from title. E.g.

const file = fs.createWriteStream(`${item.title.replace('/', '-')}.pdf`);

Upvotes: 2

Related Questions