I am a newbie to node.js (but 10 years experience with C#)
I have the following code
var http = require("http");
var url = require("url");
var path = require('path');
var fs = require("fs");
var express = require("express");
var mongo = require("./node_modules/mongo");
var Server = mongo.Server;
var Db = mongo.Db;
var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('mydb', server);
I get this exception:
Error: Cannot find module './node_modules/mongo'
at Function.Module._resolveFilename (module.js:338:15)
I also tried:
var mongo = require("mongo");
Try this instead:
var mongodb = require('mongodb');
Related
I have ran into a problem with gridfs file upload.
Basically I get this bizzare error and I have yet not found solution for solving this problem.
Here is my code that should deal with file upload:
var path = require('path');
var router = require('express').Router();
var mongoose = require('mongoose');
var serverConfig = require('../config.js');
var multiparty = require('connect-multiparty')();
var fs = require('fs');
var GridFs = require('gridfs-stream');
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs(db, mongoDriver);
router.post('/upload', multiparty, function(req, res){
console.log("file was posted");
var writestream = gfs.createWriteStream({
filename: req.files.file.name + Date.now(),
mode: 'w',
content_type: req.files.file.mimetype,
metadata: req.body
});
fs.createReadStream(req.files.file.path).pipe(writestream);
writestream.on('close', function(file){
res.status(200).json(file);
})
})
When trying to run my code, I get this error:
if (!db) throw new Error('missing db argument\nnew Grid(db, mongo)');
^
Error: missing db argument
new Grid(db, mongo)
Im using Mongoose version 4.11.12 and Gridfs-stream version 1.1.1
Does anybody know what should be done to get this thing working?
Looks like mongoose.connection.db is not pulling in the database name as it maybe missing on the connection string, your connection string should look like 'mongodb://username:password#host:port/database?options...' where database is the database you want to connect to.
alternatively you can just replace
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs(db, mongoDriver);
with
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs("myDatabase", mongoDriver);
Below is my code:The folder and filename is : gridFs/storeAudio.js.And the code is in storeAudio.js
var mongoose = require('mongoose');
var fs = require('fs');
var Grid = require('gridfs-stream');
Grid.mongo=mongoose.mongo;
//establish mongoDB connection
var conn = mongoose.createConnection('mongodb://localhost:27017/aHolyBoly');
conn.once('open',function(){
// var gfs = Grid(conn.db);
// var db = new mongo.Db('aHolyBoly', new mongo.Server("127.0.0.1", 27017));
//var gfs = Grid(db, mongo);
var writeStream = gfs.createWriteStream({
filename:'song1.mp3'
});
fs.createReadStream('../list/hero.mp3').pipe(writeStream);
writeStream.on('close',function(file){
console.log(file.filename +'Written to db');
});
});
now in the cmd inside the gridFs file I am running the command node storeAudio.js to create the database with the collection.But the following error is displayed below in the screenshot attached:
Note:I ran the following commands before:npm install gridfs-stream,npm install mongoose.
Please let me know if any more inputs are needed.
I'm trying to see a console.log message without results from the socket when someone connects to application. Here is what i have on /app.js and /bin/www files:
Just a way to return a message on console for check if the socket works on
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var session = require('express-session');
var socket = require('socket.io');
var app = express();
// socket.io
var io = socket();
app.io = io;
// var for routes
var index = require('./routes/index');
var users = require('./routes/users');
var projects = require('./routes/projects');
var messages = require('./routes/messages');
//socket message
io.on( "connection", function(socket){
console.log( "A user connected" );
});
www
var app = require('../app');
var debug = require('debug')('archiers:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
// socket.io
var io = app.io;
io.attach(server);
It would seem that you are working with some example code (rather than having written all of that yourself).
The example code you are using is quite a bit longer than it needs to be to accomplish your goals this early on.
For one thing your app.js is not "listening" on any port number - so it cannot possibly get a connection to work.
I can see your www js file would have to cause an error with process.env because the browser has no such variable.
Since you are not getting an error in your browser Console that means there must be a problem with the HTML file (which you have not posted thus far.
I expect there are other problems with the example code you are using that I have not seen.
Since you do not yet understand enough details of the code, I would suggest you start over.
You need to start with a smaller project.
Search the internet for a very small io.js example that works when you download and run it and go from there.
It will be much easier that way.
I want to create a websocket to add a communication between my angular app and my database. The app shall be able to save a question in a database & to notify the user when somebody answered.
Unfortunately I tried some tutorials which all don't work. I'm totally new to this because I use apache usually. So If you know a "working", very basic (beginner) tutorial, which doesn't require to install lots of additional things like yeoman etc. I would be glad.
In the current tutorial I get the error message:
You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.
My server.js:
var connect = require('connect'),
serveStatic = require('serve-static'),
socket = require('socket.io');
var server = connect();
server.use(serveStatic(__dirname+'/../client'));
server.listen(8080);
var io = socket.listen(server);
console.log("Server started and listen to http://127.0.0.1:8080");
without
var io = socket.listen(server);
it serves my static page.
This error is on my other approach:
has no method 'use'
My server.js
var connect = require('connect');
var http = require('http');
var serveStatic = require('serve-static');
var app = connect();
var server = http.createServer(app).use(serveStatic(__dirname+'/../client')).listen(3000);
var socket = require('socket.io');
var io = socket.listen(server);
As always if you struggle long the solution comes quick after posting. That one works for the beginning:
var connect = require('connect');
var http = require('http');
var app = connect();
var fs = require('fs');
var index = fs.readFileSync(__dirname+'/../client/index.html');
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end(index);
}).listen(3000);
var socket = require('socket.io');
var io = socket.listen(server);
I'm trying to set up this simnple NodeJS/mongodb app and I have my files structured like this:
server.js
|
+-routes/menu.js
+-routes/cases.js
In my server.js I declare my mongodb vars like this:
var express = require('express'),
mongo = require('mongodb'),
Server = mongo.Server,
MongoClient = mongo.MongoClient,
Db = mongo.Db,
http = require('http'),
app = express(),
httpServer = http.createServer(app),
bodyParser = require('body-parser'),
server = new Server('host.mongohq.com', 10066, {auto_reconnect : true}),
db = new Db('myDb', server);
db.open(function(err, client) {
client.authenticate('myUser', 'myPassword', function(err, success) {
console.log('Authenticated');
});
});
var cases = require('./routes/cases'),
menu = require('./routes/menu');
But then when I try to reference my db var in eg menu.js like this:
db.collection(myCollection, function(err, collection) {});
I get an error that db is not defined.
Obviously I can move all the mongodb declarations down to both my menu.js and cases.js file but that's just very elegant. So how do I create one mongodb instance var and refer to it from my included files?
Thanks in advance...
You need to require server.js in your menu.js file.
Your db object isn't global. If you want it to be, declare it without var.