I have a simple example:
server = http.createServer(function(req, res) {
uploads = {}
if (req.url == '/check') {
res.writeHead(200, {'content-type': 'text/plain'});
res.write(JSON.stringify(uploads));
res.end();
}
if (req.url == '/upload') {
var form = new formidable.IncomingForm();
form.on('fileBegin', function(field, file) {
var tracker = {file: file, progress: [], ended: false};
uploads[file.filename] = tracker;
file.on('progress', function(bytesReceived) {
tracker.progress.push(bytesReceived);
})
});
};
});
Why “check” return empty uploads ? Should I use global variable in this case ?
Your problem has nothing to do with global variables – when a new variable is created in JavaScript without being prefixed by
var, it is dynamically scoped AFAIK, which means it is global. Anyway, I would feel it better if your variable was indeed declared outside the function for not only being global, but for looking global too:Now, let us see your real problem: you are using formidable in a very strange way. I, for one, have never used the
on()method offormidable.IncomingForm. I would recommend you to use theparse()method, which provides you with a key-value object where the keys are the name of the<input type="file">field and the value is the upload file data, such as the path of the file in the server:IncomingForm.parse()will process all the files before call the callback. You will have all the files available, and the path to them. Of course, in this example ourtracker.progresswill contain only one bunch of data – which will be the complete file content.Also, note that the form you will use to upload the file should have the
enctype='multipart/form-data'attribute:That is it, hope this helps. Note that I am assuming that you need to solve a problem; if you want to test the
IncomingForm.on()method, however, this answer will not be much useful. I hope I have made the correct guess 🙂