Reputation: 25
When run bellow code it's give error, Reading file from directory working perfect but when pass url it's give file not found error. I've check fs.statSync accept url.
const stat = fs.statSync('http://techslides.com/demos/sample-videos/small.mp4');
Error: ENOENT: no such file or directory, stat 'http://techslides.com/demos/sample-videos/small.mp4'
Upvotes: 0
Views: 2776
Reputation: 5853
That's because its hosted on a web-server, you need to send a HTTP GET to fetch it locally.
Install the axios
package and issue a HTTP GET request to fetch the remote resource from the web-server.
npm install --save axios
Here's a program of the general idea
const fs = require('fs');
const axios = require('axios');
const { promisify } = require('util');
const writeFilePromise = promisify(fs.writeFile);
(async () => {
const url = 'http://techslides.com/demos/sample-videos/small.mp4';
const response = await axios.get(url);
if (response.data) {
await writeFilePromise('small.mp4', response.data);
}
})();
Upvotes: 0
Reputation: 708026
fs.statSync()
can take a URL, but ONLY if that URL is a file://
URL.
It is not clear what you would want to do if the argument was actually an http://
URL. You could check to see if it was not a file URL and then attempt to fetch the contents of the URL to see if it exists using a library such as got()
.
But, fetching data from another server with http will not be synchronous so you will have to change the design of your function to return a promise instead of a synchronous API.
Upvotes: 1