'How to get file size in nodejs as async await?
How to get file size in nodejs as async await ?
Here is the code for video streaming with nodejs . (and we are looking optimized performing video streaming idea's for mobile back-end API )
const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();
app.get("/video", async (req, res) => {
const path = "assets/sample.mp4";
const stat = await fs.stat(path); // here is the issue
const fileSize = stat.size;
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
if (start >= fileSize) {
res
.status(416)
.send("Requested range not satisfiable\n" + start + " >= " + fileSize);
return;
}
const chunksize = end - start + 1;
const file = fs.createReadStream(path, { start, end });
const head = {
"Content-Range": `bytes ${start}-${end}/${fileSize}`,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/mp4"
};
res.writeHead(206, head);
file.pipe(res);
} else {
const head = {
"Content-Length": fileSize,
"Content-Type": "video/mp4"
};
res.writeHead(200, head);
fs.createReadStream(path).pipe(res);
}
});
app.listen(3000, function() {
console.log("Listening on port 3000!");
});
This code have an issue on const stat=await fs.stat(path); ,
The synchronizes code working fine here like const stat=await fs.statSync(path);
how to write the fs.stat(); asynchronous ? Or any suggestions ?
Solution 1:[1]
You need to use promisesversion to use async/await. change your require to
const fs = require("fs").promises;
The default is callback style.
Solution 2:[2]
What you can do is to Promisify fs.stat and then use it in an async manner.
You can use this. util.promisify()
To make a callback method return promises, you can do this:
const fs = require("fs");
const writeFile = promisify(fs.writeFile);
const { promisify } = require("util");
async function main() {
await writeFile("/tmp/test4.js",
"console.log('Hello world with promisify and async/await!');");
console.info("file created successfully with promisify and async/await!");
}
main().catch(error => console.error(error));
You can check out this link for references.
Solution 3:[3]
May be different ans but will help you.
As you said you are optimising performing video steaming.
So website like youtube use UDP instead of TCP. You can learn about UDP Here .
If you are using node js then you can implement it using sockets
io.on('connection', function (socket) {
console.log('Socket connected: '+socket);
io.sockets.emit('msgFromAdmin', 'Hello client, this message sent from admin');
// call our main handler
streamer(socket);
});
/*
initializes ffmpeg child process which will listen on udp port:33333 for incoming frames of stream
forward video stream to client.html through socket.io
*/
var streamer = function (socket) {
var ffmpeg = require('child_process').spawn("/vagrant/nodejs-ffmpeg-livestreamer/ffmpeg-source/ffmpeg", ["-re","-y","-i", "udp://127.0.0.1:33333", "-f", "mjpeg", "-s","500x500","-pix_fmt","rgb24","pipe:1"]);
ffmpeg.on('error', function (err) {
console.log(err);
});
ffmpeg.on('close', function (code) {
console.log('ffmpeg exited with code ' + code);
});
ffmpeg.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ffmpeg.stdout.on('data', function (data) {
var frame = new Buffer(data).toString('base64');
socket.emit('render',frame);
});
};
Not have time to write code so This was code is copied from Online
FOr Full code you can visit Here
Solution 4:[4]
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
*/
Solution 5:[5]
Please use npm-multer
check this link
https://www.npmjs.com/package/multer
var upload = multer({ storage: storage, limits: { fileSize: maxSize } }).single('bestand');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Pronoy999 |
| Solution 3 | Rajan Lagah |
| Solution 4 | Ryan Almalki |
| Solution 5 | Shoaib Quraishi |
