i am using nodejs loopback framework.i want to run a cron job.i created a custom js file for this cron job in server/boot folder.but when manually i run this file(xyz). app is undefined.my code is below
var app = require('../server.js');
console.log(">>>>>>>>>>>>>>in test")
var subscription = app.models.UserNotification;
console.log(">>>>>>>>>>>..in manage")
var datasource=subscription.dataSource;
var query="SELECT DISTINCT userId FROM users_subscription";
datasource.connector.query(sql,function (err, data) {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>data is>>>>>",data);
})
here is my server.js file
var bodyParser = require('body-parser');
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
var passport = require('passport');
var bodyParser = require('body-parser').urlencoded({
extended: true
})
app.use(bodyParser)
app.use(loopback.context());
app.use(loopback.token());
var path = require("path");
var url = require('url');
var http = require('http');
var fs = require('fs');
var request = require('request');
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
app.use(loopback.static(path.resolve(__dirname, '../client')));
app.use(loopback.static(path.resolve(__dirname, '../admin')));
app.use(loopback.static(path.resolve(__dirname, '../other-dir')));
boot(app, __dirname, function(err) {
if (err) throw err;
if (require.main === module) app.start();
});
Thanks,
It's really impossible to say for sure since you don't include the code that is included with:
var app = require('../server');
(which would be the most important code to include if the require returns undefined) but if app is undefined then it means that the module is loaded but its module.exports is undefined.
Do you export anything from that module?
Are you sure that it is really app that is undefined and not, say, app.models?
Without knowing the code in question those are the most reasonable things to investigate.
Update
If you don't export anything from your server.js (which was my suspection in my answer above, but now you confirmed it with you code and comment) then after this line:
var app = require('../server.js');
you will not be able to use app.models.UserNotification
If you want to use app.models in the code that requires server.js, then you'll have to add:
module.exports.models = SOMETHING;
in your server.js code. You don't seem to have anything called models in server.js, you don't export anything as module.exports.models, so you can't expect app.models to be defined in your code that does:
var app = require('../server.js');
Related
I am creating a sample project with NodeJs and jsPDF. When I run, it echos ReferenceError: window is not defined. I also used John Gordon answer from here, but again also same problem.
I tried with
var express = require('express');
var jsPDF = require('jspdf');
var app = express();
app.get('/', function(req, res)
{
global.window = {document: {createElementNS: () => {return {}} }};
global.navigator = {};
global.btoa = () => {};
var fs = require('fs');
var jsPDF = require('jspdf');
var jsPDFTable = require('jspdf-autotable');
var doc = new jsPDF();
doc.text("Hello", 10, 10);
var data = doc.output();
fs.writeFileSync('./tmp/storage/pdf/document.pdf', data);
delete global.window;
delete global.navigator;
delete global.btoa;
});
var port = process.env.PORT || 8080;
app.listen(port);
console.log('Server started');
module.exports = app;
All you need to do is to remove your var jsPDF = require('jspdf'); at the top and to have the similar declaration inside your app.get.. (which you already have) function like this,
var express = require('express');
var app = express();
app.get('/', function(req, res)
{
global.window = {document: {createElementNS: () => {return {}} }};
global.navigator = {};
global.btoa = () => {};
var fs = require('fs');
var jsPDF = require('jspdf');
var jsPDFTable = require('jspdf-autotable');
var doc = new jsPDF();
doc.text("Hello", 10, 10);
var data = doc.output();
fs.writeFileSync('./document.pdf', data);
delete global.window;
delete global.navigator;
delete global.btoa;
});
var port = process.env.PORT || 8080;
app.listen(port);
console.log('Server started');
module.exports = app;
Hope this helps!
The specified package jspdf is a client only library and need to be used in a browser environment to work properly.
The description is clear in the package home page:
A library to generate PDFs in client-side JavaScript.
Now, the reason an npm package is available is because bundlers like Webpack and Browserify can load npm packages and convert them into a proper browser compatible script. The require() is not defined in a browser environment and will not work without these bundlers.
So, either choose a library that supports NodeJS like
https://www.npmjs.com/package/pdfkit or shift your PDF related code to browser and work with it.
EDIT:
https://github.com/MrRio/jsPDF/issues/566#issuecomment-382039316
shows that you can use the library in NodeJS env by making the following changes.
In that case, you need to define the global variables before requireing the module.
global.window = {document: {createElementNS: () => {return {}} }};
global.navigator = {};
global.btoa = () => {};
var fs = require('fs');
var jsPDF = require('jspdf');
var jsPDFTable = require('jspdf-autotable');
var app = require('express')();
app.get('/', function(req, res)
{
var doc = new jsPDF();
// ...
}
You can place the script tag either in the head or body tag in the html page, either one is fine. To decide where to place, this answer might be of help
I have a simple app where I'm trying to log to the console (terminal where I started Node, not the the browser console). Express seems to execute the route since I can see the response in my browser.
Also the logging in the app.listen(..) seems to work, but I don't see any logs afterwards.
'use strict';
// 3rd-party dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const dbSetup = require('./db-setup');
// Application config
const LOCAL_APP_PORT = 8080;
const PUBLIC_APP_PORT = process.env.PUBLIC_APP_PORT || LOCAL_APP_PORT;
global.dbType = process.env.DB_TYPE;
// Sanity check for debugging
console.log("local app port:", LOCAL_APP_PORT);
console.log("public app port:", PUBLIC_APP_PORT);
console.log("db type:", global.dbType);
// Database setup for either MongoDB or Postgres
dbSetup(global.dbType);
// Express middleware
app.use(bodyParser.json()); // for parsing application/json
// Import routes
//const index = require('./routes/index');
//const owner = require('./routes/owner');
//const shop = require('./routes/shop');
//const product = require('./routes/product');
// Set up express routes
app.use('/',(req,res,next) => {
console.log("This is not showing on the terminal.");
res.send("This is sent to the browser");
next();
})
//app.use('/owner', owner);
//app.use('/shop', shop);
//app.use('/product', product);
app.listen(LOCAL_APP_PORT, () => {
console.log('App started ...');
});
EDIT: Solved. Problem was my app was basically available on two ports at the same time. One the the public port however it was not showing any logs...
Terminal screenshot
Here is my test file:
var request = require('superagent'),
expect = require('expect'),
sinon = require('sinon'),
app = require("../../../../app");
request = request(app);
describe("HealthCheck", function () {
describe("/health_check", function () {
it("should return a 200 status", function (done) {
request
.get("http://localhost:3000/health_check")
.end(function(err, res) {
expect(res).to.exist;
expect(res.status).to.equal(200);
expect(res.body).to.contain('OK');
return done();
});
});
});
})
The error I keep running into is
1) HealthCheck /health_check should return a 200 status:
TypeError: Cannot call method 'end' of undefined
Can't figure out what I am doing wrong
Here is my app.js:
require('coffee-script/register');
var express = require('express'),
config = require('./config/config'),
fs = require('fs');
var app = express();
require('./config/express')(app, config);
app.listen(config.port);
exports.app = app;
You're exporting app as app
Therefore, when you require the module, you'll need to require the name of the function you're exporting - in this case 'app'
So, you can either change your test
var request = require('superagent'),
expect = require('expect'),
sinon = require('sinon'),
app = require("../../../../app");
request = request(app.app);
Or change your app.js to exports a single function:
Change
exports.app = app;
to
module.exports = app;
There's a good article on this here: http://openmymind.net/2012/2/3/Node-Require-and-Exports/
I am a newbie with Node and I am trying to learn how to make my modules work. Here is my express app:
var express = require('express');
var app = express();
var client = require('./config/postgres.js');
app.get('/users', function(req, res) {
var query = client.query('SELECT * FROM users');
query.on('row', function(row, result) {
result.addRow(row);
});
query.on('end', function(result) {
res.json(result);
});
});
And here is my module that I am trying to require
var pg = require('pg').native;
var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/isx';
var client = new pg.Client(connectionString);
client.connect();
module.exports.client = client;
but in my main app, my client has no method 'query'. If I just inline the code that is in the module and I am requireing in, then everything works fine. What is the difference between the 2 ways to access the code?
var client = require('./config/postgres.js');
...sets client equal to the export object in your import. Since the export object has a single client property with the query function,
client.client.query()
is what you're looking for.
If you want to export just the client, use;
module.exports = client;
Your are exporting this:
{
"client": [Function]
}
Just access the key that stores the function when you require the module or export only the function and nothing more:
module.exports = client;
I'm building a small node.js/express project and have a function in configure.js that sets configuration options in my express app. For example:
server.js
var express = require('express');
var server = ('./configure');
var app = express();
server.configure(app);
configure.js
exports.configure = function(app) {
app.set('title', 'Server');
};
This doesn't work but I hope it explains what I'm trying to do. I want to make changes to the app instance in server.js. How do I do this?
EDIT:
Okay I think i can get this all working if i understand why this isn't working. Is it to do with timing of the callback? The second console.log() isn't called.
configure.js
var fs = require('fs');
var StringDecoder = require('string_decoder').StringDecoder;
var decoder = new StringDecoder('utf8');
function configure(app) {
var config = module.exports = {};
fs.readFile('config.txt', function (err, data) {
if (err) throw err;
config.title = decoder.write(data)
console.log(config.title)
});
if(config.title) console.log(config.title);
//app.set('title', config.title)
}
module.exports = function (app) {
configure(app);
};
server.js
var express = require('express');
var cfg = require('./configure');
var fs = require('fs');
var app = express()
cfg(app)
(config.txt is echo 'server' > config.txt)
What you have should actually work.
As for your question about using multiple functions, you can export and call each separately. This can be useful when timing is important (such as if other setup steps need to occur that aren't specified in configure.js):
// configure.js
exports.configure = function (app) {
// ...
};
exports.attachMiddlware = function (app) {
// ...
};
// server.js
var express = require('express');
var server = require('./configure');
var app = express();
server.configure(app);
server.attachMiddlware(app);
You can also define a single entry function as the exported object which calls the functions needed within configure.js. This can possibly keep server.js cleaner by isolating the maintenance within configure.js:
function configure(app) {
// ...
}
function attachMiddleware(app) {
// ...
}
module.exports = function (app) {
configure(app);
attachMiddleware(app)
};
var express = require('express');
var configure = require('./configure');
var app = express();
configure(app);
I would avoid that and just do a json object:
app.js
var cfg = require('./config');
app.set('title', cfg.title);
config.js
var config = module.exports = {};
config.title = 'Server';