I have a problem to give a name to a controller to load my models:
my app.js
var express = require('express');
var app = express();
app.everyauth = require('everyauth');
app.mongoose = require('mongoose');
var fs = require('fs');
var config = require('./config.js')(app, express);
//Include models
var models = {};
fs.readdir(__dirname + '/models', function(err, files){
if (err) throw err;
files.forEach(function(file){
var name = file.replace('.js', '');
models.name = require('./models/' + name)(app.mongoose).model;
});
});
//Include controllers
fs.readdir(__dirname + '/controllers', function(err, files){
if (err) throw err;
files.forEach(function(file){
var name = file.replace('.js', '');
require('./controllers/' + name)(app, models);
});
});
app.listen(process.env.PORT || 3000);
for exemple I have test.js in models
If I want to find something in my db I would like to do:
models.test.find({}, function(err, docs){});
but it doesn't works because test is unknow, I should do
models.name.find({}, function(err, docs){});
So I would replace name by the name of the model
Thanks
Try this;
models[name] = require('./models/' + name)(app.mongoose).model;
If you want to read directory sync mode, you can use
var models = {};
var files = fs.readdirSync(__dirname + '/models');
for(var i in files) {
var name = files[i].replace('.js', '');
models[name] = require('./models/' + name)(app.mongoose).model;
}
// Now, you can use
models.test
Related
I'm developing a nodejs webapp and I have a problem.
I have a twitter.js module that expose some functions to use in other files.
My main application, app.js, import it correctly and can use the functions.
The problem is, if I import it in another .js file (via the var twitter = require(./twitter) method), it doesn't load, I can see that via console.log(twitter) and also because it doesn't recognize the functions.
This happens if app.js requires it. I copied the twitter.js file and name it differently, and if I import that it works.
How can I solve this problem?
Thanks
EDIT: Adding some code
This is the main app, app.js
var express = require("express");
var bodyParser = require("body-parser");
var path = require("path");
var twitter = require("./twitter");
var mongo = require("./mongo");
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}))
app.use(express.static(path.join(__dirname,'public')));
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));
app.get("/",function(req,res){
res.render("index.ejs")
});
app.get("/twitter",function(req,res){
twitter.getTrends(res);
});
app.post("/sendMessage",function(req,res){
twitter.postTwit(req.body.valore);
});
app.get("/pullData",function(req,res){
mongo.pullData(res);
});
app.listen(8080, function(){
console.log("server started on 8080");
});
Next is the twitter.js file:
var Twitter = require('twitter'); //import package
var mongo = require("./mongo");
var T = new Twitter({ ---developer keys here --})
exports.getTrends = function(res){
var params = { id: 23424853, count: 10}
T.get('trends/place',params,gotData);
function gotData(err,data,response){
res.render('tweets',{ data: data[0], length: 10});}
}
exports.postTwit = function(value){
T.post('statuses/update', {status:value}, function(error, tweet, response) {
mongo.pushdata(tweet.id_str);
});
}
exports.loadTwit = function(res,value){
var params = {id: value}
T.get('statuses/show/', params, function (err, data, response) {
console.log(data);
res.render('db',{ data: data});
});
}
and finally the mongo.js file, for the mongo database
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
var twitter = require('./twitter');
exports.pushdata = function(value){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var myobj = {id: value};
db.collection("tweets").insertOne(myobj, function(err, res) {
if (err) throw err;
db.close();
});
});
}
exports.pullData = function(res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("tweets").find({}).toArray(function(err, result) {
result.forEach(function(entry) {
twitter.loadTwit(res,entry);
});
db.close();
});
});
}
all these files are in the same folder.
You have created circular dependency between mongo.js & twitter.js.
mongo.js tries loading twitter.js which in turn requires mongo.js. Thats the problem. Remove this circular dependency.
Maybe you can pass the twitter object as a parameter when you call the functions of mongo.js. Or something else.
For e.g.
mongo.js
var twitter = require('./twitter');
// pass the twitter object as a parameter
exports.pullData = function(twitter, res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("tweets").find({}).toArray(function(err, result) {
result.forEach(function(entry) {
twitter.loadTwit(res,entry);
});
db.close();
});
});
}
I've have to do some maintenace on a Node.js project, and I can't get to upload a image.
I've already seen many post about uploading images into node.js but I can't figure out what happening with my code.
my routes/index.js (like my app.js)
var keystone = require("keystone");
var middleware = require("./middleware");
var importRoutes = keystone.importer(__dirname);
// Common Middleware
keystone.pre("routes", middleware.initLocals);
keystone.pre("render", middleware.flashMessages);
// Import Route Controllers
var routes = {
views: importRoutes("./views")
};
// Setup Route Bindings
exports = module.exports = function (app) {
// Views
app.get("/", routes.views.index);
app.all("/cadastroEvento", routes.views.cadastroEvento);
};
my routes/views/cadastroEvento
var keystone = require("keystone");
var async = require("async");
var env = require("../env");
var Cloudant = require("cloudant");
var multer = require("multer");
var upload = multer({ dest : "/" }).single("file");
// Conexão com o MongoDB
var Evento = keystone.list("Evento");
var mongoDb = require("mongodb");
var MongoClient = mongoDb.MongoClient;
var urlDb = env.urlDb;
exports = module.exports = function (req, res) {
var view = new keystone.View(req, res);
var locals = res.locals;
var url = view.req.originalUrl;
locals.tipo = url.substr(url.indexOf("?") + 1);
locals.section = "cadastroEvento";
locals.formData = req.body || {};
locals.validationErrors = {};
// POST
view.on("post", { action : "cadastroEvento" }, function (next) {
// Seta campos para mensagem de erro
locals.erroNome = false;
locals.erroDataInicio = false;
locals.erroDataFim = false;
locals.erroAoSalvar = false;
locals.erroAoConectar = false;
locals.eventoCadastrado = false;
locals.erroValidacao = false;
// Valida os campos
var validacao = validaCampos(req);
// HERE I DO THE UPLOAD OF THE IMAGE
upload(req, res, function(err)
{
if(err) {
return res.end("Error uploading file." + err);
}
res.end("File is uploaded");
});
console.log("Files: " + JSON.stringify(req.files));
... REST OF CODE NOT RELATED TO THE IMAGE UPLOAD ...
};
In my cadastroEvento.jade I have a form with method='post' enctype="multipart/form-data" and a input type="file" and name="file"
After the post, i receive the message: "File is uploaded"
but no image appears in my folder...
My
console.log("Files: " + JSON.stringify(req.files)); returns this:
Files: {"file":{"fieldname":"file","originalname":"Screenshot_2.png","name":"47707bab7b0b7bf03a882e88f5a0715d.png","encoding":"7bit","mimetype":"image/png","path":"C:\\Users\\JOS-HI~1\\AppData\\Local\\Temp\\47707bab7b0b7bf03a882e88f5a0715d.png","extension":"png","size":7895,"truncated":false,"buffer":null}}
Any help on where is my error would be appreciated.
Thanks
I am working on Node.js and trying to handle multiple image.
I am using following code to upload a single image and then saving the path in string format to the database.
var multiparty = require("multiparty");
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
var img = files.image[0];
var fs = require('fs');
fs.readFile(img.path, function(err, data) {
var path = "/path/to/upload/" + img.originalFilename;
fs.writeFile(path, data, function(error) {
if (error) console.log(error);
});
});
})
Now how to handle multiple image.
Any help will be appreciated!
var express = require('express'),
app = express(),
formidable = require('formidable'),
util = require('util'),
fs = require('fs-extra'),
bodyparser=require('body-parser'),
qt = require('quickthumb'),
path = require('path');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db');
var Images = require('./model.js');
app.use(qt.static(__dirname + '/'));
app.use(bodyparser());
app.set('view engine','ejs');
app.post('/upload',function (req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
});
form.on('field',function(name,value){
});
form.on('end', function(fields, files) {
for(var x in this.openedFiles)
{
//Images is my model
var img = new Images();
var temp_path = this.openedFiles[x].path;
/* The file name of the uploaded file */
var file_name = this.openedFiles[x].name;
//console.log('file '+file_name);
img.size = this.openedFiles[x].size;
img.type = this.openedFiles[x].type;
/* Location where we want to copy the uploaded file */
var new_location = 'uploads/';
console.log(img.nam=new_location+file_name);
img.save(function(err,imgobj) {
if (err)
throw err;
});
//to copy the file into a folder
fs.copy(temp_path, new_location + file_name, function(err) {
if (err) {
console.log(err);
}
});//fscopy
}//for loop
});//form end
res.send('Done!!');
});//post
app.listen(3000);
console.log('started server');
I have an working api for serving images in a route in my server.js and want to abstract it to a separate module.
before:
app.get('/api/image/:filename', function(req, res){
var resourcePath = 'uploads/public/projectnumber/issues/small/' + req.params.filename + '.png';
console.log(resourcePath)
if(fs.existsSync(resourcePath)) {
var file = fs.readFileSync(resourcePath);
res.writeHead(200, 'Content-Type:application/pdf:image/png');
res.end(file,'binary');
}
else {
res.send(400, 'No image found');
}
})
I want something like this:
var ImageRouter = require('./routes/imageRouter');
app.use('/api/image/:filename', ImageRouter);
and I've tried writing it like this in my imageRouter.js file:
var express = require('express');
var fs = require('fs');
var router = express.Router();
router.use(function(req, res, next) {
var resourcePath = 'public/images/' + req.params.filename + '.png';
if(fs.existsSync(resourcePath)) {
var file = fs.readFileSync(resourcePath);
res.writeHead(200, 'Content-Type:application/pdf:image/png');
res.end(file,'binary');
}
else {
res.send(400, 'No image found');
}
next();
});
module.exports = router;
But req.params.filename is undefined. Where have I gone wrong?
Thanks!
You should use get() on your imageRouter.js Router and prefix it on your main app.
use() is for middlewares.
Here is imageRouter.js:
var router = require('express').Router();
var fs = require('fs');
router.get('/:filename', function(req, res) {
var resourcePath = 'public/images/' + req.params.filename + '.png';
if(fs.existsSync(resourcePath)) {
var file = fs.readFileSync(resourcePath);
res.writeHead(200, 'Content-Type:application/pdf:image/png');
res.end(file,'binary');
}
else {
res.send(400, 'No image found');
}
});
module.exports = router;
And your server.js:
var express = require('express');
var app = express();
var ImageRouter = require('./routes/imageRouter');
app.use('/api/image', ImageRouter);
var express = require('express');
var routes = require('./routes');
var socket = require('socket.io');
var fs = require('fs');
var app = module.exports = express.createServer();
var Server = require('mongodb').Server,
Db = require('mongodb').Db,
Connection = require('mongodb').Connection;
var host = 'localhost';
var port = Connection.DEFAULT_PORT;
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:false});
db.open(function(err, db) {
console.log('opened');
app.listen(3000);
});
db.collection('locations', function(err, collection) {
var object= {word:'TEST'};
collection.insert(object, {safe:true}, function(err, result) {
var array = collection.findOne({word:'TEST'}, function(err, item) {});
console.log(array);// <----always "undefined"
});
});
I try to insert the object into the database. And by using "console.log(array)" everytime,I find that it always be "undefined". Is it can't be insert into the database or can't be found from the database. How can I solve it??
But, The 'console.log(item)' shows 'null'. So does it sucessfully insert into the database, or should I change another way to get the object from database.
collection.findOne is asynchronous, so you don't use the return value of the function; instead, you should console.log(item) from inside your (currently empty) callback.
db.collection('locations', function(err, collection) {
var object= {word:'TEST'};
collection.insert(object, {safe:true}, function(err, result) {
collection.findOne({word:'TEST'}, function(err, item) {
console.log(item);
});
});
});