Can't import module with require() in nodejs - node.js

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();
});
});
}

Related

how to redirect to another page from a node.js server

i have been struggling for the pas few days i want to redirect to another page from my node.js server.
first by website is redirecting me to my server to do a task but when that task is done i want the server to redirect me back to my website.
here is the node js server code.
var http = require('http');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var mongourl = "mongodb://localhost:27017/";
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
var urlQuery = url.parse(req.url, true).query;
removeItem(urlQuery.itemToRemove);
addItem(urlQuery.itemToAdd);
**// i have been trying to redirect to my html site **
**// i have got a error saying TypeError: res.redirect is not a function**
res.redirect('index.html');
res.end();
}).listen(8080);
function removeItem(remove) {
if (remove !== undefined) {
MongoClient.connect(mongourl, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = {
itemName: remove
};
dbo.collection("shoppingCart").deleteOne(myquery, function (err, obj) {
if (err) throw err;
console.log("deleted:" + myquery);
db.close();
});
});
}
}
function addItem(create) {
if (create !== undefined) {
MongoClient.connect(mongourl, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = {
itemName: create
};
dbo.collection("shoppingCart").insertOne(myobj, function (err, res) {
if (err) throw err;
console.log("document inserted:" + myobj);
db.close();
});
});
}
}
You are getting that error because response.redirect() is an express function and your app is based purely on nodejs http library.
You can accomplish what you have mentioned this way:
res.writeHead(301,{Location: 'your-location'});
res.end();
You are not creating the server properly. Try to keep your code clean,Write separate API for serving index.html, not inside creating the server.
TypeError: res.redirect is not a function
This is because res.redirect is an express function and you're using plain http node server.
You can consider using express for handling redirects for you.
var http = require('http');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var mongourl = 'mongodb://localhost:27017/';
// express
const express = require('express');
const app = express();
const port = 8080;
// for templating
// create `views/` folder
// and place `index.pug` and `redirected-page.pug`
app.set('view engine', 'pug');
app.get('/redirect', (req, res) => {
res.render('redirected-page');
});
app.get('/', (req, res) => {
var urlQuery = url.parse(req.url, true).query;
Promise.all([
removeItem(urlQuery.itemToRemove),
addItem(urlQuery.itemToAdd),
]).then(() => {
res.redirect('redirect');
});
});
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
function removeItem(remove) {
if (remove !== undefined) {
MongoClient.connect(mongourl, function(err, db) {
if (err) throw err;
var dbo = db.db('mydb');
var myquery = {
itemName: remove,
};
dbo.collection('shoppingCart').deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log('deleted:' + myquery);
db.close();
});
});
}
}
function addItem(create) {
if (create !== undefined) {
MongoClient.connect(mongourl, function(err, db) {
if (err) throw err;
var dbo = db.db('mydb');
var myobj = {
itemName: create,
};
dbo.collection('shoppingCart').insertOne(myobj, function(err, res) {
if (err) throw err;
console.log('document inserted:' + myobj);
db.close();
});
});
}
}
app.listen(port, () => console.log(`Server is running at ${port}!`));

How to correctly retrieve data using an node api of a sqlite3 database

I am coding a simple node.js application that retrieves store data from a sqlite3 database. I coded the API using express and when I test it with curl it doesn't retrieve the data.
I have tested the SQL model and it works.
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('********', (err) => {
if (err) {
return console.error(err.message);
}
console.log('Connected to the in-memory SQlite database.');
});
function recordNotFound(message) {
Error.call(this);
this.message = message;
this.status = 404;
}
var Users = function () {};
Users.prototype.getAll = function(callback) {
let sql = 'SELECT * FROM users';
db.all(sql, [], function(err, rows) {
if (err) {
console.log('chao1');
callback(err, null);
} else {
console.log('chao2');
callback(err, rows);
}
});
};
var users = new Users();
users.getAll(function(err, rows) {
console.log(rows);
callback(null, 1);
})
});
Also, when doing
SELECT * FROM users;
in the sqlite3 terminal it retrieves the information correctly.
However, in the file user_api_router.js I have,
var express = require('express');
userApiRouter = express.Router();
var Users = require('../model/users_sql_model')
var users = new Users();
userApiRouter.get('/', function(req, res) {
users.getAll(function(err, result) {
if (err) {
console.log('control1');
res.status(500).json({message: 'Error retrieving records!'});
return;
}
res.status(200).json(result);
});
});
And in the index.js file I have,
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
var usersApiRouter = require('./app/router/user_api_router');
app.use('/v1/user', usersApiRouter);
var port = 3000;
app.listen(port, function(){
console.log('listening on port ' + port);
});
When I run index.js and type
curl http://localhost:3000/v1/user
It says,
{"message":"Error retrieving records!"}
I don't know what to do to retrieve the records correctly using curl. Help me please!

How do we get response data in JSON format using node.js

I am trying to get response data from model(database) to controller
here is model
var database = require('../config/db');
exports.getAllBatch = function(done) {
database.query('SELECT batchName from batch', function (err, rows) {
if (err) return console.log(err);
else {
console.log(null, rows);
return rows;
}
})
};
here is controller
code to access data from model.
var express = require('express');
var router = express.Router();
var batch=require('../models/BatchModel');
var myParser = require("body-parser");
var app = express();
router.get('/getbatch', function(req, res, next)
{
var resp=batch.getAllBatch();
res.send(resp);
//not displaying anything on browser
});
});
How I get response on browser please guide me.Thank you in advance.
That is good code, the only thing missing is setting the body parser you have required
app.use(myParser.json())
Your functions are using a callback pattern, but you're not calling or checking the callbacks.
Model
var database = require('../config/db');
exports.getAllBatch = function(done) {
database.query('SELECT batchName from batch', function (err, rows) {
if (err) {
console.log('Err', err);
return done(err);
}
else {
console.log('Rows', rows);
return done(null, rows);
}
});
};
Controller
var express = require('express');
var router = express.Router();
var batch=require('../models/BatchModel');
var myParser = require("body-parser");
var app = express();
router.get('/getbatch', function(req, res, next) {
batch.getAllBatch(function(err, rows) {
if (err) {
res.status(500).send(err);
} else {
res.send(rows);
}
});
});

How to make MongoDB available inside Express' HTTP methods?

I'm trying to use MongoDB with Node/Express. I made the official example work:
var express = require('express')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var app = express()
// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
insertDocuments(db, function() {
db.close()
})
})
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents')
// Insert some documents
collection.insertMany([
// Some code
], function(err, result) {
// Some code
callback(result)
})
}
app.get('/insert-document', function(req, res) {
// res.send()
})
How can I make it so that Mongo is available inside Express' HTTP methods? For instance, to use insertDocuments() inside app.get('/insert-document', function(req, res)?
EDIT (full server.js file):
var express = require('express')
// var PouchDB = require('pouchdb')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var webpack = require('webpack')
var config = require('./webpack.dev.conf')
var app = express()
var compiler = webpack(config)
// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
var db
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
db = db
})
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents')
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null)
assert.equal(3, result.result.n)
assert.equal(3, result.ops.length)
console.log("Inserted 3 documents into the document collection")
callback(result)
})
}
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
stats: {
colors: true,
chunks: false
}
}))
// enable hot-reload and state-preserving
// compilation error display
app.use(require('webpack-hot-middleware')(compiler))
app.get('/docs', function(req, res) {
// res.send()
insertDocuments(db, function() {
db.close()
})
})
app.listen(8080, 'localhost', function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:8080')
})
I get
TypeError: Cannot read property 'collection' of undefined
at insertDocuments (/home/alex/node/project-mongo/build/dev-server.js:24:22)
Refer codes here, save the connection db as one global variable, sample codes as below.
var db;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
db = db;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
// Reuse database object in request handlers
app.get('/insert-document', function(req, res) {
// insertDocuments() could invoked here.
});

Inserting in mongodb with nodejs

I'm trying to insert some data in my mongodb with nodejs whenever a socket is emitted. Here is the code:
io.sockets.on( "connection",function( socket ){
socket.on( "send", function( data ) {
console.log(data.name + " and the content is: " + data.content);
mongodb.connect( "mongodb://127.0.0.1", function( err, db ) {
if(err) throw err;
var to_be_inserted = {name: data.name,content: data.content};
db.collection("chat").insert(to_be_inserted,function(err,objects){
if(err) throw err;
});
})
})
})
However whenever I go to my mongo console and type
db.chat.find()
I cannot find the inserted record. I'm sure that I have mongod open and I'm sure that the socket is emitted. Moreover the consoloe.log before the insertion does work.
Here is my mongo client
var mongodb = require("mongodb").MongoClient;
My console which runs the nodejs server does not log any error.
You should specify a database name (here: myDatabase ) and a port number (for safety).
mongodb.connect("mongodb://127.0.0.1:27017/myDatabase", function( err, db ) {
When searching the record in the mongo shell try:
use myDatabase
db.chat.find()
You forget to include the port number and database of mongodb,
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if (err) throw err;
console.log("Connected to Database");
}
try this code
var MongoClient=require('mongodb').MongoClient;
var Server=require('mongodb').Server;
var mongoc=new MongoClient(new Server("localhost",27017));
mongoc.open(function(err)
{
db.collection(<collection_name>).insert(<query>,function(err,result)
{
});
const http = require('http');
const hostname = '127.0.0.1';
const port = 8081;
var express = require("express");
var bodyParser = require('body-parser');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
app.use(bodyParser.json());
app.get('/get', function (req, res) {
res.send('Hello World')
})
var data = {
title: 'my title',
content: 'my content'
};
// This responds a POST request for the homepage
app.post('/say/:userid', function (req, res) {
var queryParameter=JSON.stringify(req.query);
res.send('Hello POST'+req.params.userid+""+queryParameter);
})
app.post('/insert', function (req, res) {
console.log(req.body);
res.send('Hello POST'+JSON.stringify(req.body));
/* var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017"; */
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbase = db.db("mydb");
var myobj = { name: JSON.stringify(req.body.name), address:JSON.stringify(req.body.address) };
dbase.collection("student").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");

Resources