Downloading Mp3 file from remote. Node js - javascript

I am trying to download a mp3 file from the remote url using node js. For that I am using the following code. But It doesn't work (File that downloading having 0 bytes only its not playing once it downloaded).
var http = require('http');
var fs = require('fs');
var url = "http://play.publicradio.org/rivet/d/podcast/marketplace/segments/2015/09/28/mp_20150928_seg_01_64.mp3";
var dest = "2.mp3";
var file = fs.createWriteStream(dest);
var request = http.get(url, function(response) {
console.log("res "+response);
response.pipe(file);
file.on('finish', function() {
console.log("File download Completed");
});
}).on('error', function(err) { // Handle errors
});

The problem here is that http doesn't follow redirects.
You can use the request npm module that does it by default to avoid handling headers yourself.
var fs = require('fs'),
request = require('request');
request
.get('http://foo.com/bar.mp3')
.on('error', function(err) {
// handle error
})
.pipe(fs.createWriteStream('2.mp3'));

Related

Save file automatically from IFrame in Node Webkit

I am using node-webkit to automate some common tasks.
I have an iframe which goes to a site address, then clicks save and I have a file save dialog pop out.
Is there any way I can catch the event to save the file witout requiring an external action (like setting the save folder and clicking on save)?
You may not be able to do it that way, but have you thought about just doing an HTTP GET request from node's http module? That's really the beauty of using node-webkit, you get to use node.js!
var http = require('http');
var fs = require('fs');
var path = require('path');
var saveLocation = path.join(__dirname, "/cache", "file.txt");
//The url we want is: 'www.random.org/integers/file.txt'
var options = {
host: 'www.random.org',
path: '/integers/file.txt'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
fs.writeFile(saveLocation, str, function (err) {
if (err) console.log("Problem Saving File.");
});
});
}
// Send the request.
http.request(options, callback).end();

Not able to upload file of 1GB from filesystem, (hardcoded file not using input type file) using xhr from Electron application using node.js

I need to upload a file reading from filesystem (not specified by the user) using xhr. Is there a way to send it via Ajax?
I understand that javascript has input type file, which gives javascript file object https://developer.mozilla.org/en-US/docs/Web/API/File.
I tried getting file descriptor using Node fs APIs (https://nodejs.org/docs/latest/api/fs.html) . But am unable to send it via xhr. Here is my code snippet.
Any help will be greatly appreciated.
var req = new XMLHttpRequest();
req.open(method, url);
req.overrideMimeType('text/xml');
var progress = 0;
req.upload.addEventListener('progress', function (event) {
if (event.lengthComputable) {
progress = Math.round(event.loaded * 100 / event.total);
}
}, false);
req.onreadystatechange = function () {
// add logic for each state
};
var fs = require('fs');
if (filename) {
// get the file descriptor and send it via xhr
fs.open(filename, "r", function(error, fd) {
// -- THIS IS THE PART NOT WORKING --
req.send(fd);
});
} else {
console.log('no filename');
}
That's not the way to read a file. This is how you do it:
var fs = require('fs');
fs.readFile(filename, { encoding : 'utf8' }, function(err, data){
//data holds the contents of the file.
req.send(data);
});

memory error in node JS (node::smalloc::Alloc)

I'm new to node Js, I've build a really simple server that send me back a zip file I request. It's all working but after some request a crash occur and i visualize this message on the terminal :
FATAL ERROR: node::smalloc::Alloc(v8::Handle, size_t, v8::ExternalArrayType) Out Of Memory
var http = require('http');
var url = require('url');
var fs = require('fs');
var port = 1337;
// create http server
var server = http.createServer(function (request, response) {
var path = require('url').parse(request.url, true);
console.log('requested ' + path.pathname);
//get zipped resoures
if (path.pathname == '/getzip') {
console.log(request.url);
var queryData = url.parse(request.url, true).query;
if (queryData.name) {
var filename = queryData.name;
//open corrisponding file
var zipFile = fs.readFileSync('packets/' + filename);
response.writeHead(200, {
'Content-Type': 'application/x-zip',
'Content-disposition': 'attachment; filename=data.zip'
});
//send file in response
response.end(zipFile);
}
else {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('{error = "bad url"}');
}
}
}).listen(port);
server.timeout = 1000000;
Do you have any idea of what it can be? this code looks so simple.
Instead of reading the entire file into memory, you should leverage streams for this:
response.writeHead(200, {
'Content-Type' : 'application/x-zip',
'Content-disposition' : 'attachment; filename=data.zip'
});
fs.createReadStream('packets/' + filename).pipe(response);

HTTP POST with a file upload

I am new to javascript/protractor and am trying to write code that posts or uploads a text file to a REST endpoint, somewhat, on the following lines. I am not able to get this to work and do not know why it is failing. Can anyone please validate this or suggest a better solution, preferably with sample code. (I have checked online and found lot of information, but was not able to apply any of that directly.)
var request = require('request');
var fs = require('fs');
var path = require('path');
var form = new FormData();
form.append('agency', 'California');
form.append('siteType', 'EF');
fileName = "test.txt";
var filePath = path.resolve(__dirname, "../resources/upload/" + fileName);
fs.writeFileSync(filePath,
"This is a test txt file");
form.append('file', fs.createReadStream(absolutePath));
request.post({url: restServiceUrl, formData: form},
function optionalCallback(err, httpResponse, body) {
if (err) {
console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});

Run file after file download complete

I am very new to node-webkit. I am using the following code to download a file. How would I go about running the file automatically when the file has finished?
var https = require('https');
var fs = require('fs');
var file = fs.createWriteStream("update_setup.exe");
var request = https.get(url + "/appdata/update_setup.exe", function (response) {
response.pipe(file);
});
Just use the writable stream's close event and spawn a child process. The event will fire once the response has completed piping to the stream.
var https = require('https');
var fs = require('fs');
var exec = require('child_process').exec;
var file = fs.createWriteStream('update_setup.exe');
var request = https.get(path, function(res) {
res.pipe(file);
});
file.on('close', function() {
exec('update_setup.exe', function(err, stdout, stderr) {
// output from starting
});
});

Categories