How to get file size using url, in nodejs
Asked Answered
R

3

7

I have some images in url(s). I can get file properties and properties include width and height of image as well. I want to get the size in bytes.

I am trying to get size using fs module as shown below, but it is not working with url, though it works with file path in local folder.

var stats = fs.statSync(url);
var fileSizeInBytes = stats["size"]
Rundle answered 3/4, 2018 at 14:15 Comment(2)
If you're not requesting a local resource, you'll need to use the http or https modules to make a request for those resources.Agonized
In addition to @Agonized keep in mind, that it could be needed to download the whole file to get the filesize, if the server is not correctly configured. Not every server returns the content-length in http header. So this is not the best idea, to get a remote file size ...Omarr
G
15

You have to use request, or http. You can get the file size by sending a HEAD request and inspect content-length field (it will not work on every server):


With curl:

curl -I "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"

You get the response:

HTTP/1.1 200 OK
Date: Tue, 03 Apr 2018 14:30:16 GMT
Content-Type: application/javascript; charset=utf-8
Content-Length: 9068
Connection: keep-alive
Last-Modified: Wed, 28 Feb 2018 04:16:30 GMT
ETag: "5a962d1e-236c"
Expires: Sun, 24 Mar 2019 14:30:16 GMT
Cache-Control: public, max-age=30672000
Access-Control-Allow-Origin: *
CF-Cache-Status: HIT
Accept-Ranges: bytes
Strict-Transport-Security: max-age=15780000; includeSubDomains
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
CF-RAY: 405c3b6e1911a8db-CDG

With request module :

var request = require("request");

request({
    url: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js",
    method: "HEAD"
}, function(err, response, body) {
    console.log(response.headers);
    process.exit(0);
});

You get the response:

{
  date: 'Tue, 03 Apr 2018 14:29:32 GMT',
  'content-type': 'application/javascript; charset=utf-8',
  'content-length': '9068',
  connection: 'close',
  'last-modified': 'Wed, 28 Feb 2018 04:16:30 GMT',
  etag: '"5a962d1e-236c"',
  expires: 'Sun, 24 Mar 2019 14:29:32 GMT',
  'cache-control': 'public, max-age=30672000',
  'access-control-allow-origin': '*',
  'cf-cache-status': 'HIT',
  'accept-ranges': 'bytes',
  'strict-transport-security': 'max-age=15780000; includeSubDomains',
  'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
  server: 'cloudflare',
  'cf-ray': '405c3a5cba7a68ba-CDG'
}
Gumboil answered 3/4, 2018 at 14:31 Comment(4)
Only works if the server is returning content-length. Not a secure aproach.Omarr
Yeah it's specified, it depend if he know which server he targetGumboil
Isn't your aproach downloading the whole file and not the headers only?! Not completely sure ...Omarr
You might want to use request.head so that it doesn't download the whole file.Hanley
T
1

file_size_url



Get file size from URL without downloading it. 0 dependencies.

Returns Promise with 'B', 'KB', 'MB', 'GB', 'TB' on success.

npm i file_size_url


import file_size_url from 'file_size_url';

file_size_url("https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/001.mp3")
    .then(console.log) // 968.27 KB
    .catch(console.error);

OR


import file_size_url from 'file_size_url';

let size = await file_size_url("https://serverjyy10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/0001.mp3")
    .catch((error) => console.log(error))

console.log(size) // 968.27 KB


Example for lop


let array = [

    'https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/001.mp3',
    'https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/002.mp3',
    'https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/003.mp3',
    'https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/055.mp3',
    'https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/110.mp3',

]

for (let index = 0; index < array.length; index++) {

    try {

        let fies_size = await file_size_url(array[index])

        if (fies_size.toString().split('.')[0] <= 95 && fies_size.toString().split(' ')[1] === 'MB') {

            console.log(fies_size + ' || <= 95 MB');

        }

        else if (fies_size.toString().split('.')[0] > 95 && fies_size.toString().split(' ')[1] === 'MB') {

            console.log(fies_size + ' || > 95 MB');

        }

        else if (fies_size.toString().split(' ')[1] === 'KB') {

            console.log(fies_size + ' || KB');

        }


    } catch (error) {

        console.log(error);

    }

}


/* output 
968.27 KB || KB
170.58 MB || > 95 MB
95.77 MB || <= 95 MB
12.21 MB || <= 95 MB
711.92 KB || KB
*/


Tatty answered 18/3, 2022 at 4:8 Comment(0)
M
0

Download the image to your ephemeral /tmp/ directory, then treat it as a regular file.

const request    = require("request"),
      fs         = require("fs"),
      remote_url = "https://example.com/image.jpg",
      path       = '/tmp/media.jpg',
      media      = request(remote_url).pipe(fs.createWriteStream(path));

media.on("finish", () => {
  return fs.statSync(path).size;
});
Matthei answered 15/5, 2020 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.