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) { ...
Related
//jshint esversion:6
var logger;
var logName;
var pollName;
var names = [];
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const readline = require('readline');
const fileName1 = __dirname + "/public/logger.json";
const fileName2 = __dirname + "/public/poll.json";
const dataWriter1 = require(fileName1);
const dataWriter2 = require(fileName2);
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
var reader = readline.createInterface({
input: fs.createReadStream(__dirname + '/public/names.txt'),
console: false
});
reader.on('line', function(line) {
names.push(line);
});
app.use(express.static(__dirname + '/public'));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.get("/route", function(req, res)
{
fs.readFile(fileName1,'utf-8',(err,data)=>
{
res.set('Content-Type', 'application/json');
res.send(data);
});
});
app.post("/", function(req, res)
{
if(req.body.button==1)
{
logName = req.body.name;
console.log(logName);
for (i = 0; i < names.length; i++)
{
if (logName == names[i])
{
logger=true;
break;
}
}
if(logger!=true)
{
logger=false;
}
dataWriter1.logger = logger;
fs.writeFile(fileName1, JSON.stringify(dataWriter1), function writeJSON(err)
{
if (err) return console.log(err);
console.log(JSON.stringify(dataWriter1));
});
logger=false;
}
else if(req.body.button==2)
{
console.log(logName);
pollName=req.body.option;
for(i=0;i<dataWriter2.list.length;i++)
{
if(dataWriter2.list[i].name==pollName)
{
dataWriter2.list[i].votes++;
dataWriter2.list[i].voter_name.push(logName);
//logName is undefined
}
}
fs.writeFile(fileName2, JSON.stringify(dataWriter2), function writeJSON(err)
{
if (err) return console.log(err);
console.log(JSON.stringify(dataWriter2));
});
}
res.redirect("/");
});
app.listen(3000, function()
{
console.log("Server Started!");
});
This is my server code in node.js. I have 2 forms in index.html and both have submit buttons with different value to differentiate. The first form has to be submitted to view the second form. My problem is that even though I'm storing a data from the first form in a variable it resets when I submit the second form even though when the server is still running.
I cannot understand why logName becomes undefined while I'm posting with the second submit button and is there any workaround?
I figured it out.. The server was restarting due to changes in a JSON file as I was running it by nodemon. Added JSON file to ignore list and now it's all fine.
I have a simple node app that parses a csv file into a string. In my server file, I call a module that runs makes a stream and pipes it into my parser.
The problem is that is code works perfectly the first time it is run, but fails after that. I've gotten a "Write after End" error so I believe there is something wrong with the stream or parser variable not being reset properly after each use. Thanks for any help!
const express = require('express');
const app = express();
const path = require('path');
const port = process.env.PORT || 3000;
const formidable = require('formidable');
const parser = require('./csvparse.js');
const fs = require('fs');
//send the index page on a get request
app.listen(port, () => console.log('Example app listening on port: ' + port));
app.get('*', (req, res) => res.sendFile(path.join(__dirname + "/index.html")));
app.post('/upload', function(req, res) {
//upload the file from the html form
var form = new formidable.IncomingForm();
form.parse(req,function(err, fields, files) {
if (err) throw err;
//get the path to the uploaded file for the parser to use
var filePath = files.spinFile.path;
parser(filePath, function(data) {
if (data == null) {
res.sendFile(path.join(__dirname + "/index.html"));
}
res.send("<code>" + data + "</code>");
});
});
});
The module export function looks like this:
module.exports = function(filePath, cb) {
var stream = fs.createReadStream(filePath);
stream.pipe(parser);
//when the stream is done, songsLog is complete and ready to be returned
stream.on('close', function() {
cb(songsLog);
});
};
Try wrapping the contents of your module.exports in another function.
module.exports = function(filepath, cb) {
function parse(filepath) {
const stream = fs.createReadStream(filepath)
etc...
}
return {
parse
}
}
then from your route, call parser.parse('file.txt') and you should have a new read stream.
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" );
});
}
I've start using NodeJS about a month ago. Since i don't have that much experience running code doesn't always go as want to. In some way i'm not able to connect to my PostgreSQL with node's pg package. (Good to know it works when i connect through PDO in PHP)
I have made this (simple) route/controller
var pg = require('pg');
var config = require('../config');
module.exports = function(app) {
app.get('/db-get-formules', function(req, res) {
var results = [];
var pgClient = new pg.Client(config.getDbConnectionString());
pgClient.connect();
pgClient.query('SELECT * FROM formules ORDER BY formule_id');
pgClient.on('row', function(row) {
results.push(row);
})
pgClient.on('end', function() {
done();
console.log(results);
res.json(results);
})
});
};
this is my index.js file in the config:
var configValues = require('./config');
module.exports = {
getDbConnectionString: function() {
return 'postgres://' + configValues.uname + ':' + configValues.password + '#' + configValues.host + ':' + configValues.port + '/' + configValues.database;
}
}
In that same config folder i have a config.json file that contains all of the parameters to connect
{
"uname": "username",
"database": "myDb",
"host": "localhost",
"password": "P#ssw0rd",
"port": "5432",
"idleTimeoutMillis": "30000"
}
If i run this /db-get-formules page the page keeps loading (spinning) and nothing really happens. What am i doing wrong?
Oh and just to provide you with my complete code, i have a server.js file in the root
var express = require('express');
var app = express();
var queryFormules = require('./controllers/queryFormules');
var port = process.env.PORT || 3000;
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/server', express.static(__dirname + '/public/server'));
queryFormules(app);
// application -------------------------------------------------------------
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
app.listen(port);
I don't see any other answers, and i'm not sure if this will help, but here is how I got it to work:
config.js
var pg = require('pg');
exports.conString = "pg://user:password#db_address:5432/db_name";
helper.js
var pg = require("pg");
var config = require('../config/config');
exports.runQuery= function(query, next) {
pg.connect(config.conString, function(err, client) {
if (err) {
var e = {
error: true,
message: "Unable to connect to database",
err: err,
};
return next(e);
}
client.query(query, function(err, result) {
//deal with the result
client.end();
return next(some_data_or_value);
});
});
}
Then you can call runQuery from anywhere, ofcourse you'll need to deal with the results / possible errors in the function as well.
some other file or function
var helpers = require('../services/helpers');
var query = "SELECT * FROM formules ORDER BY formule_id"
helpers.runQuery(query, function(result) {
//deal with results
});
How do I get the caller ID from twilio? I've tried many different ways to get the POST data but it isn't working.
var twilio = require('./node_modules/twilio/index'),
http = require('http'),
express = require('express');
http.createServer(function (req, res) {
/*
var app = express();
app.use(express.urlencoded());
app.post('/call',function (req, res) {
*/
var name, from;
// if (req.method=='POST')
// req.on('From', function (data) {from = data;});
try {
from = req.param('From');
// from = req.body.from;
}
catch (err)
{
console.log("No Caller ID");
}
console.log("Number: " + from);
//Some code goes here..
res.end(resp.toString());
}).listen(8080);
It's throwing me the error every single time at the try catch statement (always null).
I'm trying to get the caller ID of an incoming text message.
Things in comments are the different approaches I tried.
The thrown error is:
Error TypeError: Object #IncomingMessage> has no method 'param'
I guess that this will do the trick:
var qs = require('querystring');
var processRequest = function(req, callback) {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
callback(qs.parse(body));
});
}
var http = require('http');
http.createServer(function (req, res) {
processRequest(req, function(data) {
// data
});
}).listen(9000, "127.0.0.1");