I am relatively new on Node JS. I am working on an application fetching XML-files from a server. In summary I want to do this:
I am able to use jsftp.get to download files to a local directory, but I am not able to get the downloaded data as a string.
What am I doing wrong?
My code is like this:
var http = require("http");
var url = require("url");
var JSFtp = require("jsftp");
var myStrToReturn = new String();
http.createServer(function(req, res) {
// URL
var parsedUrl = url.parse(req.url, true);
var queryAsObject = parsedUrl.query;
var str = new String();
var myFunction = queryAsObject["function"];
var Ftp = new JSFtp({
host: "ftp.ftp.ftp",
port: 21, // defaults to 21
user: "user", // defaults to "anonymous"
pass: "passwd", // defaults to "@anonymous"
debugMode: true
});
var str = "";
Ftp.get("Production/Offers/datafile.xml", function(err, socket) {
if (err) return;
socket.on("data", function(d) { str += d.toString(); })
socket.on("close", function(hadErr) {
if (hadErr)
console.error('There was an error retrieving the file.');
});
socket.resume();
});
myStrToReturn = str.toString("binary");
res.writeHead(200, {
'Content-Encoding':'utf-8',
'charset' : 'utf-8',
'Content-Type': 'text/plain;charset=utf-8'});
res.write(myStrToReturn.toString());
res.end();
console.log(myStrToReturn);
});
Ftp.on('jsftp_debug', function(eventType, data) {
console.log('DEBUG: ', eventType);
console.log(JSON.stringify(data, null, 2));
});
}).listen(8030);
console.log("Server listening on port 8030");
Download is asynchronous so when you reach to
myStrToReturn str.toString("binary");
its value is undefined this is why you will get an error when you are trying to use toString.
Solution for that is to use promises or use the mystrToReturn only inside socket.on("close",...