I am following the node tutorial on https://dev.to/achowba/build-a-simple-app-using-node-js-and-mysql-19me , to build a node application with Mysql. I'm getting the error "ENOENT path: public/assets/img/image name" which I have been able to trace to the line uploadedFile.mv('public/assets/img/${image_name}', (err ) => { in the file player.js.
I have tried fs.writeFile and fs.copyFile to no avail. Any help will be appreciated.
PLAYER.JS
const fs = require('fs');
module.exports = {
addPlayerPage: (req, res) => {
res.render('add-player.ejs', {
title: "Welcome to Socka | Add a new player"
,message: ''
});
},
addPlayer: (req, res) => {
if (!req.files) {
return res.status(400).send("No files were uploaded.");
}
let message = '';
let first_name = req.body.first_name;
let last_name = req.body.last_name;
let position = req.body.position;
let number = req.body.number;
let username = req.body.username;
let uploadedFile = req.files.image;
let image_name = uploadedFile.name;
let fileExtension = uploadedFile.mimetype.split('/')[1];
image_name = username + '.' + fileExtension;
let usernameQuery = "SELECT * FROM `players` WHERE user_name = '" + username + "'";
db.query(usernameQuery, (err, result) => {
if (err) {
return res.status(500).send(err);
}
if (result.length > 0) {
message = 'Username already exists';
res.render('add-player.ejs', {
message,
title: "Welcome to Socka | Add a new player"
});
} else {
if (uploadedFile.mimetype === 'image/png' || uploadedFile.mimetype === 'image/jpeg' || uploadedFile.mimetype === 'image/gif') {
uploadedFile.mv(`public/assets/img/${image_name}`, (err ) => {
if (err) {
return res.status(500).send(err);
}
// send the player's details to the database
let query = "INSERT INTO `players` (first_name, last_name, position, number, image, user_name) VALUES ('" +
first_name + "', '" + last_name + "', '" + position + "', '" + number + "', '" + image_name + "', '" + username + "')";
db.query(query, (err, result) => {
if (err) {
return res.status(500).send(err);
}
res.redirect('/');
});
res.redirect('/');
});
});
} else {
message = "Invalid File format. Only 'gif', 'jpeg' and 'png' images are allowed.";
res.render('add-player.ejs', {
message,
title: "Welcome to Socka | Add a new player"
});
}
}
});
}
Related
Am a newbie to node.js, have somewhat figured out the LDAP authentication. Here am trying to retrieve employee ID from the search but none of the search entries are fetched though the passed credentials are bounded successfully , not sure where i'm mislead. If someone could help me out in it would be of a great help!
Below are the result sets of the code snippet:
Reader bind succeeded
Search results length: 0
Search
retval:{"messageID":2,"protocolOp":"LDAPResult","status":0,"matchedDN":"","errorMessage":"","referrals":[],"controls":[]}
No unique user to bind
ldapRoute.route('/ldap').post((req, res, next) => {
var result = "";
var email =req.body.email;
var client = ldap.createClient({
url: 'ldap://******'
});
var opts = {
filter: '(sAMAccountName='+ email + ')',
attributes: ['sAMAccountName']
};
var username = 'ii' + "\\" + email;
client.bind(username, req.body.password, function(err) {
if (err){
result += "Reader bind failed " + err;
res.send(result);
return;
}
else{
result += "Reader bind succeeded\n";
}
client.search('OU=emp,dc=i,dc=ac,dc=com', opts, function(err, searchRes) {
var searchList = []
if (err) {
result += "Search failed " + err;
res.send(result);
return;
}
searchRes.on("searchEntry", (entry) => {
result += "Found entry: " + entry + "\n";
searchList.push(entry);
});
searchRes.on("error", (err) => {
result += "Search failed with " + err;
res.send(result);
});
searchRes.on("end", (retVal) => {
result += "Search results length: " + searchList.length + "\n";
for(var i=0; i<searchList.length; i++)
result += "DN:" + searchList[i].employeeID + "\n";
result += "Search retval:" + retVal + "\n";
if (searchList.length == 1) {
client.bind(searchList[0].employeeID, req.body.password, function(err) {
if (err)
result += "Bind with real credential error: " + err;
else
result += "Bind with real credential is a success";
res.send(result);
}); // client.bind (real credential)
} else {
result += "No unique user to bind";
res.send(result);
}
});
});
});
});
The issue was in the filters and for some strange reasons the 'end' got fired before hitting the 'searchEntry', debugging it helped me to resolve the issue.
//Filter
var opts = {
filter: '(sAMAccountName=' + email+')',
scope: 'sub',
attributes: ['employeeID']
};
//Search
client.search('OU=empl,dc=ii,dc=ac,dc=in', opts, function(err, searchRes)
{
if (err)
{
result += "Search failed " + err;
res.send(result);
return;
}else{
searchRes.on("searchEntry", (entry) =>
{
result += "Found entry: " + entry.object.employeeID;
res.send(result);
}
/ ........../
} });
As part of my project, I have to create text files which have to be downloaded as a ".txt".
I am using Node.js and React JavaScript, and I have already tried using the Node.js "fs.writeFile", but the browser doesn't recognize the download, the file name is always being called as the folder name and the file is always empty although the variable is a string and not empty.
I'm calling from the client to this function:
app.post("/downloadnetworks", async (req, res) => {
let selectedApps=req.body.selectedApps;
let arr=await sqlFunctions.createByIds(selectedApps);
res.send();
module.exports.createByIds = (productsArray) => {
return new Promise(function(resolve, reject) {
var bulkedString = '';
var product;
for (let obj of productsArray) {
let query = "select * from...........";
con.query(query, function(err, result, fields) {
if (err) throw err;
let stringifiedJson = JSON.stringify(result)
let parsedJson = JSON.parse(stringifiedJson)
The DB data is being added into the variable 'stringifiedJson', and it continues from here:
let parsedJson = JSON.parse(stringifiedJson) //has all the data from the DB
for (let network of parsedJson) {
if (network.certification_Id) {
bulkedString += network.domain_Name + ", " + network.publisher_Id + ", " + network.relationship + ", " + network.certification_Id;
} else {
bulkedString += network.domain_Name + ", " + network.publisher_Id + ", " +
network.relationship;
}
bulkedString += "\n";
product = network.product;
}
})
fs.writeFile('C:\Work\App ads.txt\App-Ads Files\'' + product + '.txt', bulkedString, 'utf8', (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
}
resolve(bulkedString)
})
}
hi everyone I tried to develop chat app using node js and socket.io for back end , my problem is empty value of associated array
socket.on('nickName', (data) => {
console.log(data)
var roomId;
con.query("SELECT user_id FROM nickname WHERE user_id = '" + String(data) + "'", (err, result) => {
if (err) {
throw err;
}
console.log(result)
if (result == undefined || result[0] == undefined) {
con.query("INSERT INTO nickname (user_id,socket_id) VALUES ('" + data + "','" + socket.id + "')")
} else {
con.query("UPDATE nickname SET socket_id = '" + socket.id + "' WHERE user_id = '" + data + "' ", (err, result) => {
})
}
})
con.query("SELECT * FROM room WHERE user_id = '" + data + "'", (err, result) => {
if(err){
throw err;
}else{
io.to(socket.id).emit('getChatList', { "chatList": result })
var unread = {}
result.forEach(Element=>{
roomId = Element.room_name
con.query("SELECT COUNT(*) FROM message WHERE room_id = '"+roomId+"' AND seen=0 AND to_user='"+data+"'",(err,unseen)=>{
if(err){
throw err;
}else{
// I trying set value to unread array
unread[roomId] =unseen[0]['COUNT(*)'] ;
// unread array work correctly
console.log(unread)
}
})
// problem is here print unread empty ({})in
// console.
console.log(unread)
})
}
})
});
unread array show empty value but when I put for example unread['A'] ='C' ; out of query block everything works fine , anyone can help me?
I solved my problem by using async.each() instead of result.forEach()
socket.on('nickName', (data) => {
console.log(data)
var roomId;
clients[data] = socket.id;
con.query("SELECT user_id FROM nickname WHERE user_id = '" + String(data) + "'", (err, result) => {
if (err) {
throw err;
}
console.log(result)
if (result == undefined || result[0] == undefined) {
con.query("INSERT INTO nickname (user_id,socket_id) VALUES ('" + data + "','" + socket.id + "')")
} else {
con.query("UPDATE nickname SET socket_id = '" + socket.id + "' WHERE user_id = '" + data + "' ", (err, result) => {
})
}
})
con.query("SELECT * FROM room WHERE user_id = '" + data + "'", (err, result) => {
if(err){
throw err;
}else{
io.to(socket.id).emit('getChatList', { "chatList": result })
var unread = {};
asyncc.each(result,function(Element,callbackk){
roomId = Element.room_name
console.log(Element)
con.query("SELECT COUNT(*) FROM message WHERE room_id = '"+Element.room_name+"' AND seen=0 AND to_user='"+data+"'",(err,unseen)=>{
if(err){
throw err;
}else{
console.log(unseen)
console.log(Element.room_name)
unread[Element.room_name] = unseen[0]['COUNT(*)'] ;
}
callbackk();
})
},function(er){
console.log(unread)
})
}
})
});
Whenever I'm trying to redirect my node.js file (form.js) to the same page using res.redirect("/"); it is working!
But when I'm trying to redirect to a different file(welcome.ejs) in the same folder using res.redirect("/welcome"); it is not working.
My welcome.ejs file has this sentence in it <h1>Welcome Home</h1> and that's it.
My mysql database is working just fine and I can see the message "rows affected". So I'm pretty sure there is no issue there.
I'm not even getting any errors.
I cannot understand why I cannot redirect to welcome.ejs page but I can redirect to home page(home.ejs or "/"). In the browser the message says "cannot get /welcome"
I even tried return res.redirect(/welcome) or res.redirect("/welcome.ejs") but it didn't work!
my folder structure is views/home.ejs & views/welcome.ejs.
Can anyone please help me with this?
this is my form.js code
app.get('/accountform', function(req, res) {
var q = "SELECT COUNT(*) AS count FROM `Projects`";
connection.query(q, function(err, results){
if (err) throw err;
var count = results[0].count;
//res.send("We have " + count + " no of users.");
res.render("accountform", {count: count});
});
app.post('/addproject', function(req, res){
var project = {
Project_No: req.body.Project_No,
Project_Name: req.body.Project_Name,
Status: req.body.Status,
Project_Type: req.body.Project_Type
};
connection.query('insert into `Projects` SET ?', project, function(err,
result){
console.log(err);
console.log(result);
res.redirect("/welcome");
});
});
});
I try something near to your code
this is my app.js
const {getHomePage} = require('./routes/index');
const {addPlayer} = require('./routes/player');
app.get('/', getHomePage);
app.post('/add', addPlayer);
routes/index.js
module.exports = {
getHomePage: (req, res) => {
let query = "SELECT * FROM `players` ORDER BY id ASC";
db.query(query, (err, result) => {
if (err) {
res.redirect('/');
}
res.render('index.ejs', {
title: "Welcome to Socka | View Players"
,players: result
});
});
},
};
routes/player.js
module.exports = {
addPlayerPage: (req, res) => {
res.render('add-player.ejs', {
title: "Welcome to Socka | Add a new player"
,message: ''
});
},
addPlayer: (req, res) => {
if (!req.files) {
return res.status(400).send("No files were uploaded.");
}
let message = '';
let first_name = req.body.first_name;
let last_name = req.body.last_name;
let position = req.body.position;
let number = req.body.number;
let username = req.body.username;
let uploadedFile = req.files.image;
let image_name = uploadedFile.name;
let fileExtension = uploadedFile.mimetype.split('/')[1];
image_name = username + '.' + fileExtension;
let usernameQuery = "SELECT * FROM `players` WHERE user_name = '" + username +
"'";
db.query(usernameQuery, (err, result) => {
if (err) {
return res.status(500).send(err);
}
if (result.length > 0) {
message = 'Username already exists';
res.render('add-player.ejs', {
message,
title: "Welcome to Socka | Add a new player"
});
} else {
if (uploadedFile.mimetype === 'image/png' || uploadedFile.mimetype ===
'image/jpeg' || uploadedFile.mimetype === 'image/gif') {
uploadedFile.mv(`public/assets/img/${image_name}`, (err ) => {
if (err) {
return res.status(500).send(err);
}
let query = "INSERT INTO `players` (first_name, last_name,
position, number, image, user_name) VALUES ('" +
first_name + "', '" + last_name + "', '" + position + "', '"
+ number + "', '" + image_name + "', '" + username + "')";
db.query(query, (err, result) => {
if (err) {
return res.status(500).send(err);
}
res.redirect('/');
});
});
} else {
message = "Invalid File format. Only 'gif', 'jpeg' and 'png' images
are allowed.";
res.render('add-player.ejs', {
message,
title: "Welcome to Socka | Add a new player"
});
}
}
});
}
}
i have index.ejs and addplayer.ejs in views folder
this is my full github code
https://github.com/gayathribrittany/nodeapp
Here is line 54, where I am getting the error:
if (docr.emails) {
And here is the rest of my original code:
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var config = require('./config'),
xlsx = require('./xlsx'),
utils = require('./utils'),
_ = require('lodash'),
url = config.DB_URL;
var meetings = [];
function findNumberOfNotesByMeeting(db, meeting, callback) {
var meetingId = meeting._id.toString(),
meetingName = meeting.name.displayValue,
attendees = meeting.attendees;
host = meeting.host;
var count = 1, pending = 0, accepted = 0;
console.log("==== Meeting: " + meetingName + '====');
_.each(attendees, function(item) {
console.log(count++ + ': ' + item.email + ' (' + item.invitationStatus + ')');
if (item.invitationStatus == 'pending') { pending++; }
else if (item.invitationStatus == 'accepted') { accepted++; }
});
console.log("*** " + attendees.length + ", " + pending + "," + accepted);
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, doc) {
var emails = [];
if (doc.emails) {
doc.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
db.collection('notes').find({ 'meetingId': meetingId }).count(function(err, count) {
if (count != 0) {
console.log(meetingName + ': ' + count + ',' + attendees.length + ' (' + email + ')');
meetings.push([ meetingName, count, email, attendees.length, pending, accepted ]);
}
callback();
});
}
});
}
function findMeetings(db, meeting, callback) {
var host = meeting.host;
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, docr) {
var emails = [];
if (docr.emails) {
docr.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
var cursor = db.collection('meetings').find({
'email': {'$regex': 'abc', '$options': 'i' }
});
}
cursor.count(function(err, count) {
console.log('count: ' + count);
var cnt = 0;
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
findNumberOfNotesByMeeting(db, doc, function() {
cnt++;
if (cnt >= count) { callback(); }
});
}
});
});
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findMeetings(db, function() {
var newMeetings = meetings.sort(function(m1, m2) { return m2[1] - m1[1]; });
newMeetings.splice(0, 0, [ 'Meeting Name', 'Number of Notes', 'Emails' ]);
xlsx.writeXLSX(newMeetings, config.xlsxFileNameMeetings);
db.close();
});
});
Try the following:
function findMeetings(db, meeting, callback) {
var host = meeting.host;
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, docr) {
var emails = [];
if (!err && docr && docr.emails) {
docr.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
...