loopback model access in custom js file - javascript

i want to access a model name userRegistration in my custom js file but every time its showing undefined and shows this error
TypeError: Cannot call method 'findOne' of undefined
please Check code
var loopback = require('loopback');
var app = loopback();
var nodemailer = require("nodemailer");
var smtpTransport = require("nodemailer-smtp-transport");
var path=require('path');
var fs=require('fs');
var Handlebars = require('handlebars');
exports.mailToUser=function(req,res,next){
var userNotification = app.models.UserNotification;
var userregister = app.models.UserRegistration;
userregister.findOne({where:{email:email}},function(err,userobj){
if(err){
next()
}
})
}
Thanks

You shouldn't use var app = loopback();
If you want to access to app you can require your server.js or some other ways existed. The simple one is requiring server

Related

how to use global variable(sharable variables) in Node.js&Express

I have a file called data.js for keeping data as memory database.
var express = require('express');
var app = express();
var aList;
var bList;
var cList;
module.exports = app;
And I want to initialise data when I start the server. So, I implemented init() in app.js
...
var data = require('./data'); // data.js is located in the same folder.
app.set(...);
app.use(...);
...
init();
...
});
fun init(){
console.log("Hello!");
aList = getDumpDataList(10); // I also tried with 'data.aList = getDumpDataList(10);' but didn't work.
console.log(JSON.stringify(aList));
}
fun getDumpDataList(n){
var list;
... // for loop to generate random elements.
return list;
}
module.exports = app;
When I printed with console.log(), Hello! is printed but aList isn't printed but undefined
And I also want to use the data in routers under routes folder.
So, what I did is.
...
var data = require('./data');
route.get("/...", function(req, res, next){
console.log(JSON.stringify(aList));
...
});
But it is also undefined.
I am just making simple test server that initialise data whenever I re-run.
How can I share variables between the js files?
You do not export those vars:
const express = require('express');
const app = express();
let aList;
let bList;
let cList;
module.exports.app = app;
module.exports.aList = aList;
module.exports.bList = bList;
module.exports.cList = cList;
...but i would not put express in data.js, rather put it in app.js.
I would also initialize those vars with initial values in data.js, if the initial data does not depend on something else.
Last but not least: Do not use var anymore, use let and const instead. It is supported since Node 6+ (https://node.green/). I replaced it in the code.

node.js call ws.send from controller

i want to send a websocket, using express-ws out from a different controller, not by route and I have the following code in the server.js:
var SocketController = require('./routes/ws.routes');
var app = express();
var server = require('http').createServer(app);
var expressWs = require('express-ws')(app);
app.ws('/', SocketController.socketFunction);
the SocketController looks like that:
exports.socketFunction = function (ws, req) {
ws.on('message', function(msg) {
console.log(msg);
ws.send("hello");
});
}
Is it possible to call the
ws.send()
event from another controller? How do i get the "ws" object?
thanks!
You will have to store your sockets in memory. To access stored sockets from different modules, you can store references for these sockets in a separate module.
For example, you can create a module socketCollection that stores all the active sockets.
socketCollection.js:
exports.socketCollection = [];
You can import this module where you define your web socket server:
var socketCollection = require('./socketCollection');
var SocketController = require('./routes/ws.routes');
var app = express();
var server = require('http').createServer(app);
var expressWs = require('express-ws')(app);
expressWs.getWss().on('connection', function(ws) {
socketCollection.push({
id: 'someRandomSocketId',
socket: ws,
});
});
app.ws('/', SocketController.socketFunction);
Now every time new client connects to the server, it's reference will be saved to 'socketCollection'
You can access these clients from any module by importing this array
var socketCollection = require('./socketCollection');
var ws = findSocket('someRandomSocketId', socketCollection);
var findSocket = function(id, socketCollection) {
var result = socketCollection.filter(function(x){return x.id == id;} );
return result ? result[0].socket : null;
};

middleware not working on connect HTTP server

I am reading Professional Node.js and i'm trying to understand connect HTTP middleware framework. I created a simple middleware that returns a function that replies with a custom test string:
function replyText(text) {
return function(req, res) {
res.end(text);
};
}
module.exports = replyText;
But when i try to use this middleware in a connect server. Node gives me an error:
/Users/socomo22/work/hello_world_app_v2.js:8
var app = connect.createServer(replyText('Hello World!'));
^
TypeError: undefined is not a function
But when i simply use:
var app = connect();
app.listen(8080)
It runs without giving any error. I don't understand whether i'm doing any syntatical mistake. How would i use this simple middleware? This is my connect server file:
var connect = require('connect');
// middlewares
var replyText = require('./reply_text');
var app = connect();
var app = connect.createServer(replyText('Hello World!'));
app.listen(8080, function() {
console.log('listening on 8080 port')
});
As pointed by documentation use use API to mount a middleware and a http module to create an instance of server although you can create an instance just with connect as pointed here.
As pointed by #FranciscoPresencia adding .js extension while you require a your local module is optional.
var replyText = require('./reply_text.js');
So your code should look like this and i tested it. Working as intended
var connect = require('connect')
var http = require('http')
var app = connect();
// middlewares
var replyText = require('./reply_text.js');
app.use(replyText('Hello World!'));
http.createServer(app).listen(8080, function() {
console.log('listening on 8080 port')
});
Note: Try to avoid ports like 8080, 80 etc as its a reserved ports that might be used by other apps. This sometimes may cause node to fail.
Adding the output screenshot for your reference
Here You can start server in this way...
var connect = require('connect');
var http = require('http');
var app = connect();
var replyIN = require('./connetFile.js')
app.use(replyIN('Hello there m back again'));
http.createServer(app).listen(8888,function(){console.log('Server has started');});
And this is your connectFile.js
function replyIN(text){
return function (req, res) {
res.end(text);
};
};
module.exports = replyIN;

Node.js. Error: module is not a function

i have a main file -- index.js:
var express = require('express');
var app = express();
var request = require('request');
var demo = require('demo');
// This app will only respond requests to the '/scrape' URL at port 3000.
app.get('/scrape', function (req, res) {
var url = "http://www.l.com";
request(url, function (error, response, html) { // two parameters: an URL and a callback
if (!error) {
demo(html);
}
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
and my module is demo.js:
module.exports = function (html) {
....
return JSON.stringify(json);
}
The error is :
TypeError: demo is not a function
I am new to node.js, i would like to know why this didn't work. Maybe i dont understand the real principle of module?
Thank you for answer me first.
You're not exporting your module properly. It should be:
exports.demo = function ....
Try to include your demo module in index.js:
var demo = require('./demo.js');
For the other freshers who use module in node.js for the first time.
first, made a new module called the name of your module.js
Second, it is not necessary to do "
npm install demo --save", if you want, it is also okay.
Third, in the main js which u want to call this module, focus on the name and the path of the module, you should write var anyName = require('the name of your module');, if they are in the same directory, you should write like this: var anyName = require('./the name of your module');

Unable to export variables within function expressjs/requestjs

My export code
//export.js
var express = require('express'),
fs = require('fs'),
request = require('request'),
cheerio = require('cheerio'),
app = express();
var episode = [],
title = [],
synopsis = [],
reviews = [],
date = [];
exports.showGrab = function(url,response){
request(url,response, function(error, response, html){
var $ = cheerio.load(html),
shows = {bitten:['http://www.tv.com/shows/bitten-2013/episodes/']};
$('.no_toggle._clearfix').eq(1).filter(function(){
var data = $(this);
episode = data.children().first().children().last().text();
exports.episode = episode;
})
})
}
console.log(episode); // => defined as [] not the value given in the function
//import.js
var express = require('express'),
fs = require('fs'),
request = require('request'),
cheerio = require('cheerio'),
app = express(),
server = require('./export');
console.log(server.episode);
server.showGrab('http://www.tv.com/shows/bitten-2013/episodes/');
within the import script using the function server.showGrab works fine but I need access to the variables within the show grab function in my import script. I believe this problem boils down to a scope issue, if I export variables outside a function they work fine but I was under the impression that declaring variables the way I have done would make them global. How can I run this function in the import script whilst still passing it a url and getting back episode to work with?
#Pointy you were right the import script was calling the value before it was defined
//import.js
if (server.episode === undefined){
var test = setInterval(function(){
if (server.episode != undefined){
clearInterval(test);
}
console.log(server.episode);
}, 1000);
}
this does the trick, for some reason using else instead of wrapping an if in an if does not work.

Categories