i uploading file using restify api.
it gives me error,
{ "code": "internalerror", "message": "this socket closed." }
the read api still works great unable upload image. possible issue?
the code using,
exports.uploadfile = function (req, res, next) { var file_name = req.files.image.name; var file_name_arr = file_name.split('.'); var imageextension = file_name_arr.pop(); var imagename = date.now()+"."+imageextension; var newpath = process.cwd() + "/images/" + imagename; fs.readfile(req.files.image.path, function (err, data) { fs.writefile(newpath, data, function (err){ if(err) return next(err); res.json({ image: imagename }) return next(); }); }); }
after digging bit, here found answer. above code reads entire file memory , write on disk slow. rather have used streaming write file works charm.
replacing fs.readfile in above code with
rr = fs.createreadstream(req.files.image.path).pipe(fs.createwritestream(imagepath)) rr.on('error', function(err){ console.log(error) }); rr.on('finish', function(){ //do ur work here });
reference link: https://nodejs.org/api/stream.html
other way use fs.rename faster above specified method doesn't have read file @ all.
fs.rename(req.files.image.path, new_file_path);
Comments
Post a Comment