Ple3ska
Ple3ska

Reputation: 13

readFileSync can't find file from URL

I'm trying to download a file (without saving it) and convert it, but readFileSync throws an error that the file can't be found: "Error: ENOENT: no such file or directory, open 'https://s3.amazonaws.com/appforest_uf/f1631452514756x615162562554826200/testdoc.txt'"

Code:

var path = require('path');
const fs = require('fs');
const https = require('https');

const file_x = 'https://s3.amazonaws.com/appforest_uf/f1631452514756x615162562554826200/testdoc.txt';
var filename = path.basename(file_x);

const FileBuffer = fs.readFileSync(file_x);
const fileParam = {
    value: FileBuffer,
    options: {
      filename: filename,
      contentType: 'application/octet-stream'
    }
};

console.log(fileParam);

And I get the error the file can't be found... The URL is working OK, do I need to do something else to download from URL ?

Upvotes: 0

Views: 1815

Answers (2)

bfdes
bfdes

Reputation: 101

Did you try looking for similar questions? For example, readFileSync not reading URL as file. There it is clearly stated that the fs API only deals with local files.

You will need to use the https module to stream the file.

Upvotes: 2

Tyler2P
Tyler2P

Reputation: 2370

The package fs only reads files, not URLs. Alternatively, you can use a package like axios. Axios allows you to make HTTP requests within node.js.

Example usage:

const axios = require('axios');
axios.get('https://s3.amazonaws.com/appforest_uf/f1631452514756x615162562554826200/testdoc.txt').then(response => {
    console.log(response);
    ...
});

Upvotes: 2

Related Questions