I have a problem with node js rtsp streaming server - node.js

I made rtsp cctv streaming server with nodjs.
But it is not stable.
Some cctvs works well but others are not.
First I thought rtsp url has its own problem, but it may not.
Because the url worked well in vlc player.
I don't know what I'm missing.
below is my whole code related cctv streaming.
var express = require('express');
var router = express.Router();
var kill = require('tree-kill');
var fs = require('fs');
var path = require('path');
var ffmpeg = require('fluent-ffmpeg');
var ffmpegInstaller = require('#ffmpeg-installer/ffmpeg');
ffmpeg.setFfmpegPath(ffmpegInstaller.path)
var streams = {};
//start cctv
router.post('/', (req, res) => {
var cname = req.body.cname;
var url = req.body.url;
//if there is same cctv name
if(streams[cname] != null) {
res.status(409).send("duplicate name");
return;
};
//create dir as given cctv name;
mkdir(cname);
stream = ffmpeg(url).addOptions([
'-hls_time 5',
'-hls_list_size 10',
'-hls_flags delete_segments',
'-f hls'
]).output('./public/video/' + cname + '/' + cname + '.m3u8'); //save path
console.log("Start cctv streaming");
stream.on('error', function(err, stdout, stderr) {
console.log("cctv has been stoped");
console.log(err);
});
stream.run();
streams[cname] = stream;
res.status(201).send("OK");
});
//bring cctv pid by cctv name
router.get('/:cname', (req, res) => {
var cname = req.params.cname;
if(streams[cname] == null) {
res.status(404).send("not found such a cctv");
return;
};
var pid = streams[cname].ffmpegProc.pid;
res.send({"pid": pid});
});
//stop cctv by pid
router.delete('/:cname', async (req, res) => {
var cname = req.params.cname;
//no cctv
if(streams[cname] == null) {
res.status(404).send("not found such a cctv");
return;
};
//del dir
var filePath = './public/video/' + cname;
fs.rmdir(filePath, { recursive: true }, (err) => {
if (err) {
console.log(err)
} else {
console.log('dir is deleted.');
}
});
//var pid = streams[cname].ffmpegProc.pid;
streams[cname].kill();
res.status(204).send("OK");
});
const mkdir = (name) => {
var root = './public/video/';
if(!fs.existsSync(root + name)){
fs.mkdirSync(root + name);
}
}
And this is ts file save folder.
cctv1 dosen't work well but cctv2 works well.
(cctv1 started first but created less ts file than cctv2.)

Related

make pdf file from jsPDF and send pdf file to server node js

i have code to make pdf and succeeded in downloading and opening it, but i want to send pdf to my server on node js, and i have made app.post on server but i can't make pdf become base64 and save it on server
in frontend
<script type="text/javascript">
function genPDF() {
html2canvas(document.getElementById('testDiv')).then(function (canvas) {
var img = canvas.toDataURL('image/png');
var doc = new jsPDF('landscape');
doc.addImage(img, 'png', 10, 10);
var temp = doc.save('test.pdf');
var post = new XMLHttpRequest();
post.open("POST", "/receive");
post.send(temp);
}
</script>
Download PDF
in server
app.post('/receive', function (request, respond) {
var body = '';
var filePath = './static' + '/document/Document.pdf';
//
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var data = body.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile(filePath, buf, function (err) {
if (err) throw err
respond.end();
});
});
});
how to send var temp = doc.save('test.pdf'); server and generate pdf to base64?
Use the below code this will help you.
IN FE
<script type = "text/javascript">
function genPDF() {
html2canvas(document.getElementById('testDiv')).then(function (canvas) {
var img = canvas.toDataURL('image/png');
var doc = new jsPDF('landscape');
doc.addImage(img, 'png', 10, 10);
var temp = doc.save('test.pdf');
var data = new FormData();
data.append("pdf_file", temp);
var post = new XMLHttpRequest();
post.open("POST", "/receive");
post.send(data);
}
</script>
<a href = "javascript:genPDF()" > Download PDF </a>
IN BE
const fs = require('fs');
const multipartMiddleware = require('connect-multiparty')();
const express = require('express');
const app = express();
const port = 8000;
const filePath = './static' + '/document/Document.pdf';
app.post('/', multipartMiddleware, (request, response) => {
fs.readFile(request.files.pdf_file.path, (err, data) => {
fs.writeFile(filePath, data, function (err) {
if (err) throw err;
response.send('Done')
});
})
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
});

YouTube - MP4 to MP3 messes up

It's supposed to download all the videos in the playlist and convert them to mp3. But all this does is make the mp4's and 1 empty mp3 with a number higher than the max mp4. My newbie brain doesn't know how to fix this...
var ytpl = require('ytpl');
var fs = require('fs-extra');
var path = require('path');
var ffmpeg = require('fluent-ffmpeg');
var binaries = require('ffmpeg-static');
var ytdl = require('ytdl-core');
var output_dir = path.join(__dirname+"/dl");
ytpl("PL8n8S4mVUWvprlN2dCAMoIo6h47ZwR_gn", (err, pl) => {
if(err) throw err;
let c = 0;
pl.items.forEach((i) => {
ytdl(i.url_simple+"", { filter: 'audioonly' }).pipe(fs.createWriteStream(output_dir+"/"+c+".mp4")).on('finish', () => {
console.log("Finished MP4 DL, starting conversion...");
ffmpeg(output_dir+"/"+c+".mp4")
.setFfmpegPath(binaries.path)
.format('mp3')
.audioBitrate(320)
.output(fs.createWriteStream(output_dir+"/"+c+".mp3"))
.on('end', () => {
console.log("Finished MP3 Convert...");
})
.run();
});
c++;
});
});
Fixed using an example by ytdl-core Link
Fixed code:
var ytpl = require('ytpl');
var fs = require('fs-extra');
var path = require('path');
var ffmpeg = require('fluent-ffmpeg');
var binaries = require('ffmpeg-static');
var sanitize = require('sanitize-filename');
var ytdl = require('ytdl-core');
var output_dir = path.join(__dirname+"/dl");
ytpl("PL8n8S4mVUWvprlN2dCAMoIo6h47ZwR_gn", (err, pl) => {
if(err) throw err;
for (const i of pl.items) {
let stream = ytdl(i.id, {
filter: 'audioonly'
});
ffmpeg(stream)
.audioBitrate(320)
.save(`${output_dir}/${sanitize(i.title + " (by " + i.author.name + ")")}.mp3`)
.on('end', () => {
console.log("Done! Downloaded \""+i.title + " (by " + i.author.name + ")"+"\"");
});
}
});

how to send multiple image object to client in node express?

I am new in angular. I have a set of images & I want to display it on to the client browser on a load of the page.
Is it possible or not?
I am able to send a single file but not multiple files now I am stuck can someone help me.
Thanks for help
router.get('/getList', function(req, res, next) {
var fileNames = [];
fileNames = readDir.readSync('/NodeWorkspace/uploads/output/', ['**.png']);
var data = {};
fileNames.forEach(function(filename) {
filepath = path.join(__dirname, '../../uploads/output') + '/' + filename;
fs.readFile(path.join(__dirname, '../../uploads/output') + '/' + filename, function(err, content) {
if (!err) {
console.log(content);
}
});
});
//res.sendFile(path.join(__dirname,'../../uploads/output/', fileNames[0]));
response.data = fileNames;
res.json(response);
});
Convert fs callback to promise and read all parallel once done send response.
const fs = require('fs');
const db = require('../db');
const readFile = util.promisify(fs.readFile);
router.get('/getList', function (req, res, next) {
var fileNames = [];
fileNames = readDir.readSync('/NodeWorkspace/uploads/output/', ['**.png']); // use async function instead of sync
var data = {};
const files = fileNames.map(function (filename) {
filepath = path.join(__dirname, '../../uploads/output') + '/' + filename;
return readFile(filepath); //updated here
});
Promise.all(files).then(fileNames => {
response.data = fileNames;
res.json(response);
}).catch(error => {
res.status(400).json(response);
});
});

File upload nodejs to server

I want to upload files of my form to my server.
I have already test this but i haven't a success.
What is the best npm module for that ?
Can i test it in localhost ?
Thanks
For Express Use,
https://www.npmjs.com/package/multer
For Hapi.js
https://gist.github.com/joyrexus/0c6bd5135d7edeba7b87
Hope This Helps!
Using Hapijs
I have done Image upload in one of my projects
I had Used Nginx to define my root location for this file upload.
var mkdirp = require('mkdirp');
var path = require('path');
var mv = require('mv');
exports.imageUpload = function (req, reply) {
var payload = req.payload;
commonImageUpload(payload.uploadFile,urid,function(err,res){
});
}
var commonImageUpload = function (file, idUser, callback) {
if (null != file) {
var extention = path.extname(file.filename);
var extentionsList = [];
extentionsList.push('.jpg');
extentionsList.push('.png');
extentionsList.push('.jpeg');
extentionsList.push('.gif');
var index = extentionsList.indexOf(extention.toLowerCase());
if (index < 0) {
callback(true,"Invalid Media Type");
} else {
var filepath;
filepath = '../cdn/idcard/';
var fname = filepath + idUser + extention;
console.log(fname);
mkdirp(filepath, function (err) {
if (err) {
console.log(err);
callback(true,"Internal Server Error");
}
else {
mv(file.path, fname, function (err) {
});
}
});
}
} else {
callback(true);
}
}
Let me know if this solves your problem.

node phantomjs seo running via node write the file

I'm wondering if this is the write way:
node.js
var fs = require('fs');
var path = require('path');
var childProcess = require('child_process');
var phantomjs = require('phantomjs');
var binPath = phantomjs.path;
var childArgs = [
path.join(__dirname, 'phantomjs-runner.js'),
'http://localhost:3000'
]
childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
if(err){
}
if(stderr){
}
fs.writeFile(__dirname+'/public/snapshots/index.html', stdout, function(err) {
if(err) {
console.log(err);
}
else {
console.log("The file was saved!");
}
});
});
phantomjs-runner.js
var system = require('system');
var url = system.args[1] || '';
if(url.length > 0) {
var page = require('webpage').create();
page.open(url, function (status) {
if (status == 'success') {
var delay, checker = (function() {
var html = page.evaluate(function () {
var body = document.getElementsByTagName('body')[0];
if(body.getAttribute('data-status') == 'ready') {
return document.getElementsByTagName('html')[0].outerHTML;
}
});
if(html) {
clearTimeout(delay);
console.log(html);
phantom.exit();
}
});
delay = setInterval(checker, 100);
}
});
}
may be could be a better way like
clearTimeout(delay);
fs.writeFile
phantom.exit();
How can I manage ie
different urls and different files
I mean
http://localhost:3000 index.html
http://localhost:3000/blog blog.html
http://localhost:3000/blog/postid postid.html
ENDED UP
'use strict';
var fs = require('fs'),
path = require('path'),
childProcess = require('child_process'),
phantomjs = require('phantomjs'),
binPath = phantomjs.path,
config = require('../config/config');
var env = (process.env.NODE_ENV === 'production') ? 'production' : null,
currentPath = (env) ? config.proot + '/build/default/snapshots' : config.proot + '/default/snapshots';
function normalizeUrl(url){
if( (typeof url === 'undefined') || !url){
return '';
}
if ( url.charAt( 0 ) === '/' ){
url = url.substring(1);
}
return '/'+url.replace(/\/$/, "");
}
function normalizePage(route){
if(!route){
return 'index';
}
var chunks = route.substring(1).split('/');
var len = chunks.length;
if(len===1){
return chunks[0];
}
chunks.shift();
//I get the id
return chunks[0];
}
module.exports = function (url) {
var route = normalizeUrl(url);
var page = normalizePage(route);
var childArgs = [
path.join(__dirname, './phantomjs-runner.js'),
config.url+route
];
childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
if(err){
}
if(stderr){
}
fs.writeFile(currentPath + '/' + page + '.html', stdout, function(err) {
if(err) {
console.log(err);
}
else {
console.log("The file was saved!");
}
});
});
};
So I worked out for the parameters I'm still
waiting for way to get the output ^^

Resources