I want to upload the file from ajax to node.js.code is working perfectly.but it shows deprecated.like
(node:7016) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
what is the problem in nodejs code.can anyone solve the issue?Thankyou
var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'views/index.html'));
});
app.post('/upload', function(req, res){
console.log("get");
var form = new formidable.IncomingForm();
form.multiples = true;
form.uploadDir = path.join(__dirname, '/uploads');
form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name));
});
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});
form.on('end', function() {
res.end('success');
});
form.parse(req);
});
var server = app.listen(8086, function(){
console.log('Server listening on port 3000');
});
fs.rename() is asynchronous and takes a callback which is called when the rename is done. Node is warning you because you are ignoring this, which is usually a mistake.
You should probably at least check for errors, which should make the warning go away:
form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name), function(err){
console.log("Error renaming file:", err );
}
});
More here: https://nodejs.org/api/fs.html
fs asynchronous functions now demand a callback. You can fix your code by updating this line:
fs.rename(file.path, path.join(form.uploadDir, file.name));
by this one:
fs.rename(file.path, path.join(form.uploadDir, file.name),(error) => { /* handle error */ }))
You can check below documentation as well.
see https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
Related
I can't read a file with this code that I've found on internet...
var express = require('express');
var app = express();
var fs = require('fs');
var port = 8080;
app.get('/', function(req, res) {
fs.readFile('./queries/anagconti_clienti_giorni.txt', 'utf8', function(err, data) {
if (err) {
res.send(err);
} else {
res.send(data);
}
});
});
var server = app.listen(port, function() {
console.log("Started on http://localhost:" + port);
});
The error that it give to me is:
{
"errno":-4058,
"code":"ENOENT",
"syscall":"open",
"path":"C:\Users\AlessandroGolin\Desktop\Mia\Visual_Studio\server_link\queries\anagconti_clienti_giorni.txt
"}
What could be causing this error??
Please cross check the path or permission of "./queries/anagconti_clienti_giorni.txt" file. If file not exist then create your "queries" folder at same level where your above code file exist.
I have problem when I use formidable parse function. In my project, I use httpsys (not build-in http module) to create server (for port sharing), and then I send a post request with multipart form data(including string and zip file). Then I want to use formidable to parse request body. But parse function callback does not be called. There is no error. I do not use Express application, but I use Express Router to route my requests. I already use error handler to catch error, but it never be called (form.on('error', function(err) { console.log(err); });). Anyone has same problem? Please help me out, thanks in advance.
// main.js
var router = express.Router();
router.use(function (req, res, next) {
for (var i in req.headers) {
req.headers[i] = querystring.unescape(req.headers[i]);
req.headers[i] = req.headers[i].replace(/\+/g, "");
}
next();
});
//router.use(bodyParser());
router.post('/TestServer/' + 'TestRequest', function(req, res) {
testRequestHandler.execute(req, res);
});
var server = require('httpsys').http().createServer(router);
var port = '80'; // or other port
var listeningPort = 'http://localhost:' + port + '/TestServer/';
server.listen(listeningPort );
// In testRequestHandler
var execute = function(req, res) {
var form = new Formidable.IncomingForm();
form.uploadDir = uploadDir.getPath();
form.encoding = Constants.ENCODING_UTF8;
form.on('file', function(name, file) {console.log('file='+file);});
form.on('error', function(err) { console.log(err); }); // never be called
form.on('aborted', function() { console.log('Aborted'); });
form.parse(req, function(err, fields, files) {
//todo test code
console.log( "parse finished" );
});
}
So I followed this answer and made it to the last step, correctly I think. But then what? I'm trying to run a node file, but it doesn't appear to be in the file listed at the PATH directory. How am I supposed to get it in that folder?
My node entry file:
'use strict';
var express = require("express");
var child_process = require("child_process");
var app = express();
app.get("/go", function(req, res, next) {
var stream = child_process.spawn("node file.js").on("error", function(error) {
console.log("Error!!! : " + error);
throw error;
});
});
app.get("/", function(req, res, next) {
console.log("Hit main page.");
res.end("Got me.");
});
app.listen( (process.env.PORT || 4000), function() {
console.log("Example app listening on Heroku port " + process.env.PORT + " or local port 4000!");
});
And file.js, the file I'm attempting to open:
'use strict';
function sayHello() {
console.log("Hello.");
}
sayHello();
In your spawn method, you should have:
app.get("/go", function(req, res, next) {
var stream = child_process.spawn("node", ["file.js"]).on("error", function(error) {
console.log("Error!!! : " + error);
throw error;
});
});
my code at Gist: https://gist.github.com/yhagio/10654836
I'm new to Express, tried from the example of the book "Node.js in Action - Chapter.9"(Uploading photo).
The author uses Express version "3.4.0" but I used "3.4.8" and I ran into this issue,
The Error message when I try to upload images:
500 TypeError: Cannot read property 'photo' of undefined
routes/photos.js
...
exports.submit = function (dir) {
return function (req, res, next) {
var img = req.files.photo.image; // ---- This 'photo' part is undefined
var name = req.body.photo.name || img.name;
var path = join(dir, img.name);
fs.rename(img.path, path, function (err) {
if (err) { return next(err); };
Photo.create({
name:name,
path:req.name
}, function (err) {
if (err) { return next(err); };
res.redirect('/');
});
});
};
};
but I found that in my app.js (bodyParser() is no longer used since 3.4.8)
app.js(In my code Express 3.4.8)
...
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json()); // Instead of bodyParser()
app.use(express.urlencoded()); // Instead of bodyParser()
...
But in author's code has bodyParser().
app.js(Author uses Express 3.4.0
...
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser()); // This is no longer used in latest version
So, I was wondering if I can fix this issue by using multer (http://expressjs-book.com/forums/topic/replacement-for-bodyparser-connect-multipart/):
app.use(express.json());
app.use(express.urlencoded());
app.use(multer({ dest: './public/photos' })); // I tried this
This didn't solve. Please help me. Thank you.
UPDATE: Solution I figured out
This code worked(routes/photos.js)
exports.submit = function (dir) {
return function(req, res, next){
var form = new multiparty.Form();
form.parse(req, function(err, fields, files){
var img = files.image[0];
var name = fields.name || img.originalFilename;
var path = join(dir, img.originalFilename);
fs.rename(img.path, path, function(err){
if(err){return next(err); };
Photo.create({
name: name,
path: img.originalFilename
}, function(err){
if(err){return next(err); };
res.redirect('/');
});
});
});
};
};
Have you given node-multiparty a try? Here's example usage from the README:
var multiparty = require('multiparty')
, http = require('http')
, util = require('util')
http.createServer(function(req, res) {
if (req.url === '/upload' && req.method === 'POST') {
// parse a file upload
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);
The author (Andrew Kelley) recommends avoiding bodyParser, so you're right to avoid it, but multiparty seems to solve a similar issue for me.
The reason it no longer works is because the node-formidable library is no longer included in Express. If you want to continue using formidable, follow these instructions.
The proper way to use body-parser with Express 4.x is:
var express = require('express'),
bodyParser = require('body-parser'),
app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
To access the files:
var formidable = require('formidable'),
form = new formidable.IncomingForm();
exports.submit = function (dir) {
return function (req, res, next) {
form.parse(req, function(err, fields, files) {
// The files object here is what you expected from req.files
});
});
});
Note: if you're trying to use multiple, set:
form.multiples = true;
What i am trying to do ::
I am trying to move the uploaded file to /public/images
My request::
My app.js code
var express=require('express');
var mysql=require('mysql');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var app=express();
var connection=mysql.createConnection({
host:'localhost',
user:'******',
password:'******',
database:'*********'
});
connection.connect();
app.set('port',process.env.PORT||7002);
app.use(express.bodyParser());
app.post('/Details/',function(req,res){
var file_name=req.files.key.originalFilename;
console.log(file_name);
crypto.randomBytes(8, function(ex, buf) {
var array = req.files.key.originalFilename.split('.');
var type = array[array.length - 1];
var name = buf.toString('hex') + '.' + type;
fs.rename(req.files.key.path, './public/images/' + name, function(e) {
next(e, name);
});
});
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
Error i am facing::
next(e, name)......... "next" not defined
How to resolve this ?
What exactly do you want to do? I think that instead of calling next, you want to generate a response back to the client.
So instead of this:
next(e, name);
Do this:
if (e) {
res.send(500, e.message);
} else {
res.send(WHATEVER_YOU_WANT_TO_SEND_AS_RESPONSE);
}
If you really want to call next, you need to add it to the callback function's argument list:
app.post('/Details/', function(req, res, next) { ...