I am creating a web application using node js that can download videos from facebook, i am getting the url and quality using express using the code below but how can i download it
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
app.get('/', (req,res)=>{
res.sendFile(path.join(__dirname,'templates','index.html'));
});
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/send_data', function(req, res) {
res.send('You sent the name "' + req.body.fbUrl + ' in '+req.body.quality+' Quality".');
if(req.body.quality == "HD")
{
download_video("HD");
}
else if(req.body.quality == "SD")
{
download_video("SD");
}
else if(req.body.quality == "MP3")
{
download_video("MP3");
}
else
{
app.get('/', (req,res)=>{
res.sendFile(path.join(__dirname,'templates','index.html'));
});
}
function download_video(quality)
{
console.log('video is downloading in "'+req.body.quality+'" Quality');
}
I don't know how are you getting the FB video URL explicitly. However, I can help you with how to download video from URL,
let http = require('http');
let fs = require('fs');
let download = (url, dest, cb) => {
let file = fs.createWriteStream(dest);
http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb);
});
});
}
This will create a file stream and download the file chunk by chunk to the destination path (dest).
Related
I am making an API for my minecraft server and have been able to get as far as getting the JSON file to update what I send it in a POST request. I would like to know if it is possible to only update on key of the JSON file.
This is my current code:
var fs = require('fs');
var fileName = './serverStatus.json';
var file = require(fileName);
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const cors = require('cors');
const { fileURLToPath } = require('url');
app.get('/status', alldata);
function alldata(request, response) {
response.send(file);
}
app.post('/status', (req, res) => {
if (!req.is('application/json')) {
res.status(500);
res.send('500 - Server Error');
} else {
res.status(201);
fs.writeFile(
fileName,
JSON.stringify(req.body, null, 4),
function writeJSON(err) {
if (err) return console.error(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
}
);
res.send(file);
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>
console.log(`Server running on: http://localhost:${PORT}`)
);
and my JSON file:
{
"lobby": "offline",
"survival": "offline",
"creative": "offline"
}
Thanks in advance!
You could use fs.readFileSync or to read file content.
Then update your JSON content such as jsonData["survival"] = "online".
Final, write content back to file with fs.writeFile. (See note-1)
You could see the following example code.
const fs = require("fs");
// 1. get the json data
// This is string data
const fileData = fs.readFileSync("./serverStatus.json", "utf8")
// Use JSON.parse to convert string to JSON Object
const jsonData = JSON.parse(fileData)
// 2. update the value of one key
jsonData["survival"] = "online"
// 3. write it back to your json file
fs.writeFile("./serverStatus.json", JSON.stringify(jsonData))
Note-1: Because you save data in file, you need to write the whole data when you want to update file content.
But, if you want to get the latest file content after you write your new data into file, you should fs.readFileSync your file again like following code to avoiding any modified which are forgot to save.
app.get('/status', alldata);
function alldata(request, response) {
const fileContent = fs.readFileSync(fileName, "utf8");
const fileJsonContent = JSON.parse(fileContent)
// do other stuff
response.send(fileContent);
}
var fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
var fileName = './serverStatus.json';
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// maybe use this instead of bodyParser:
//app.use(express.json());
const cors = require('cors');
const { fileURLToPath } = require('url');
app.get('/status', alldata);
function alldata(request, response) {
response.send(file);
}
app.post('/status', (req, res) => {
if (!req.is('application/json')) {
res.status(500);
res.send('500 - Server Error');
} else {
// read full config file:
var src = fs.readFileSync(fileName);
// convert src json text to js object
var srcObj = JSON.parse(src);
// convert req json text to js object
var reqObj = JSON.parse(req.body);
// update the src with the new stuff in the req
for(var prop in reqObj){
srcObj[prop] = reqObj[prop];
}
// update any additional things you want to do manually like this
srcObj.bob = "creep";
// convert the updated src object back to JSON text
var updatedJson = JSON.stringify(srcObj, null, 4);
// write the updated src back down to the file system
fs.writeFile(
fileName,
updatedJson,
function (err) {
if (err) {
return console.error(err);
}
console.log(updatedJson);
console.log('updated ' + fileName);
}
);
res.send(updatedJson);
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>
console.log(`Server running on: http://localhost:${PORT}`)
);
//res.status(201);
I have a (React) js app that reads a PDF file using FileReader then uses fetch to send it to a node js server running Express. When the request is received on the server side, however, the request body is undefined. What is missing from my code for this to work?
Client side:
function readFile() {
let file = fileInputRef.current.files[0];
const reader = new FileReader();
return new Promise((resolve) => {
reader.onload = function (e) {
resolve(e.target.result);
};
reader.readAsDataURL(file);//readAsDataURL, readAsArrayBuffer, or readAsBinaryString?
});
}
function handleSubmit(event) {
event.preventDefault();
readFile().then((value) => {
fetch('/gen/file', {
method: 'POST',
body: value
})
});
Server side:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const app = express();
const jsonParser = bodyParser.json()
const port = 3000;
app.post("/gen/file", function (req, res, next) {
console.log(req.body);//undefined - Why????
});
app.listen(port, function (err) {
if (err) console.log(err);
});
Client Side:
function getBase64(file,callback){
const reader = new FileReader();
reader.addEventListener('load',()=> callback(reader.result));
reader.readAsDataURL(file);
}
function handleSubmit(event) {
event.preventDefault();
let body = {};
getBase64(file,fileUrl=>{
body.file = fileUrl;
fetch('/gen/file', {
method: 'POST',
body
})
})
Server Side:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const app = express();
const jsonParser = bodyParser.json()
const port = 3000;
const fs = require('fs');
app.post("/gen/file", function (req, res, next) {
console.log(req.body);//undefined - Why????
let file = req.body.file;
let base64 = file.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var buffer = new Buffer.from(base64[2],'base64');
fs.writeFile(__dirname+"/out.jpeg", buffer, 'base64', function (err) {
console.log(err);
});
});
I am having error uploading my file. I get response that i have a file in my request body but it doesn't get uploaded
My code
const fs = require('fs')
const express = require('express')
const app = express();
const fileUpload = require('express-fileupload')
var http = require('http')
// var stream = fs.createReadStream(__dirname+'/files/1576350919658.jpeg');
var path = require('path')
app.use(fileUpload())
app.post('/',(req,res,next)=>{
console.log(req.files)
let file = req.files.image;
file.mv(__dirname+'/files', (err)=>{
if(err){
return res.send(err)
}
return res.send('File Uploaded')
})
})
app.listen(2020)
console.log('listening')
Error:
{
"errno": -4068,
"code": "EISDIR",
"syscall": "open",
"path": "D:\\wd\\javascript\\Projects\\uploadFiles\\files"
}
const fs = require('fs')
const express = require('express')
const app = express();
const fileUpload = require('express-fileupload')
var http = require('http')
// var stream = fs.createReadStream(__dirname+'/files/1576350919658.jpeg');
var path = require('path')
app.use(fileUpload())
app.post('/',(req,res,next)=>{
console.log(req.files)
let file = req.files.image;
file.mv(__dirname+'/files/ddddd.jpg', (err)=>{
if(err){
return res.send(err)
}
return res.send('File Uploaded')
})
})
app.listen(2020)
console.log('listening')
convert you image into base64 data .
var base64Data = req.body.file_data // base64 string
var file_name='123.png';
var file_dir = "assets/client_folios/"
var fs = require("fs");
if (!fs.existsSync('assets/')){
fs.mkdirSync('assets/');
}
if (!fs.existsSync(file_dir)){
fs.mkdirSync(file_dir);
}
var file_path="assets/client_folios/"+file_name
var file_path="assets/client_folios/"+file_name
fs.writeFile(file_path, base64Data, 'base64',async function(err) {
}
I can upload a file via postman and download a file from server in two different service .. But what i need is ..In a single call i should able to upload the file to server ,then perform some operation after performing some operation i should able to download the file automatically.
Here is my code.
My firsts service(file upload operation)
var express = require('express');
var fs = require('fs');
var formidable = require('formidable');
var router = express.Router();
/* GET home page. */
router.post('/', function(req, res, next) {
var form = new formidable.IncomingForm();
form.uploadDir="./file"
form.keepExtensions=true;
form.maxFileSize=10*1024*1024;
form.multiples=false;
form.parse(req, function (err, fields, files) {
res.write('File uploaded');
res.end();
});
});
module.exports = router;
Download service
var express = require('express');
var router = express.Router();
var express = require('express');
router.get('/', function(req, res, next) {
var file = './file/myOutput.txt';
var name = 'ENC.txt'
res.download(file, name);
});
module.exports = router;
Now i need to make this two service as one?
var express = require('express');
var formidable = require('formidable');
var app=express();
async function calculation(parameters)
{
if(parameters)
{
//Here you can do calculation depending upon parameter values
}
else
{
//Display error or as per your choice
}
}
app.get('/',function(req,res){
res.sendFile(__dirname+'/index.html');
});
async function cal(res,file,form)
{
try{
const data = await calculation(true)
if(data){
res.set({
'Location' : __dirname+'/index.html',
});
res.download( __dirname+file.name);
}
}
catch(error)
{
console.log(error);
}
}
app.post('/',function (req,res){
var form = new formidable.IncomingForm();
form.parse(req);
form.on('fileBegin',function(name,file){
file.path = __dirname+file.name;
console.log("Uploading");
});
form.on('file',
function(name,file)
{
console.log('Uploaded ',file.name);
cal(res,file);
});
});
Hope it helps
I am using Both Java web server and node js(for chat)
Now I want to make voice call using Twilio`
I wrote code like this
var fs = require('fs');
var sslOptions = {};
var path = require('path');
var express = require('express');
var app = express();
var server = require('https').createServer(sslOptions, app);
const EventEmitter = require('events');
const myEE = new EventEmitter();
server.on("request", function (req, res) {
res.end("this is the response");
});
server.listen('8090', function(){
console.log("Secure Express server listening on port 8090");
});
var accountSid = 'AC***************************';
var authToken = "******************************";
var client = require('twilio')(accountSid, authToken);
var morgan = require('morgan');
var bodyParser = require('body-parser');
var twilio = require('twilio');
var VoiceResponse = twilio.twiml.VoiceResponse;
module.exports = server;
app.use(express.static(path.join(process.cwd(), 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(morgan('combined'));
app.get('/', function(request, response) {
response.render('index');
});
app.post('/call', function(request, response) {
var salesNumber = request.body.salesNumber;
var url = 'http://' + request.headers.host + '/outbound/' + encodeURIComponent(salesNumber);
var options = {
to: '+91*******',
from: '+17******',
url: url,
};
client.calls.create(options)
.then((message) => {
response.send({
message: 'Thank you! We will be calling you shortly.',
});
})
.catch((error) => {
console.log('errot');
// console.log(error);
response.status(500).send('error');
});
});
app.post('/outbound/:salesNumber', function(request, response) {
var salesNumber = request.params.salesNumber;
var twimlResponse = new VoiceResponse();
twimlResponse.say('Thanks for contacting our sales department. Our ' +
'next available representative will take your call. ',
{ voice: 'alice' });
twimlResponse.dial(salesNumber);
response.send(twimlResponse.toString());
});
I am trying to make an ajax call from one of my javascript files to an express route
$.ajax({ url: '/call',
method: 'POST',
dataType: 'application/json',
processData: false,
data: {
phoneNumber: '+91*******',
salesNumber:'+17******** '
}
}).done(function(data) {
// The JSON sent back from the server will contain a success message
alert(data.message);
}).fail(function(error) {
//alert('errot');
alert(JSON.stringify(error));
});
when I execute this ajax call
it's looking for Java server and return 404 error
How can I solve this issue
Anyone, please help me to solve this issue