app.get not defined when calling a separate .js file node.js - javascript

Here is the app.js file:
var cluster = require("cluster");
if (cluster.isMaster) {
var cpuCount = require("os").cpus().length;
for (var i = 0; i < cpuCount; i++) {
cluster.fork();
}
cluster.on("exit", function() {
console.log("A cluster died\n A cluster was created!");
cluster.fork();
});
} else {
var bcrypt = require("bcrypt"),
bodyParser = require("body-parser"),
express = require("express"),
session = require("express-session"),
isemail = require("isemail"),
nodemailer = require("nodemailer"),
path = require("path"),
r = require("rethinkdbdash")({
port: 28015,
host: "localhost",
db: "FPC"
}),
socket = require("socket.io");
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var login = require(path.join(__dirname + "/config/login.js"));
}
Here is the config/login.js file
app.get('/login',function(req, res){
res.sendFile(path.join(__dirname+'/www/CreateAccount/index.html"));
});
When I try to launch the app it gives me an error
ReferenceError: app is not defined
at Object.<anonymous> (C:\Users\yeet\Documents\Projects\website\config\login.js:1:63)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\yeet\Documents\Projects\website\app.js:29:3)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:423:7)
I can't figure out why it won't just take var app = express from the app.js. And requiring all the needed modules to run this removes the purpose of making login.js it's own file

Related

node.js throws error when I try to require local module

Where am I going wrong while requiring a local module?
Below are my code snippets for requiring a local module.
I have placed the game.js file in the following path /public/javascript/game.js whereas the app.js is being placed in the following path /app.js
//game.js
let players = [];
let selectedPlayers = [];
let remainingPlayers = 11;
for(var i=0; i<2; i++){
players.push($(".card > button").eq(i).attr("value"));
}
exports.players = players;
//app.js
const express = require("express");
const bodyParser = require("body-parser");
const mySql = require("mySql");
const game = require("./game");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
app.get("/play", function(req, res){
res.render("PlayGame");
console.log(game.players);
});
app.listen(process.env.PORT || 3000, function(req, res){
console.log("Listening on port 3000");
});
When I run this, I get the following error in my terminal
internal/modules/cjs/loader.js:883
throw err;
^
Error: Cannot find module './game'
Require stack:
- C:\Users\akash\Desktop\FantasyCricket\app.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Users\akash\Desktop\FantasyCricket\app.js:4:14)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'C:\\Users\\akash\\Desktop\\FantasyCricket\\app.js' ]
}
They are not on the same folder, so your require must be:"
const game = require("./public/javascript/game");

Node js error: [nodemon] app crashed - waiting for file changes before starting

After importing the expressEdge I got stucked.
const path =require('path');
const expressEdge = require('express-edge');
const express = require('express');
const app = new express();
app.use(express.static('public'));
app.use(expressEdge);
app.set("views", `${__dirname}/views`);
app.get('/', (req, res) => {
res.render('index')
})
app.get('/about.html', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/about.html'));
})
app.get('/contact.html', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/contact.html'));
})
app.get('/post', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/post.html'));
})
app.listen(5000, () => {
console.log('App listening o port 5000');
})
while trying to introduce the expressEdge I got these error below:
at Object.<anonymous> (C:\Users\Globalwise\Desktop\nodejs-blog\index.js:11:5)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
Your help would be appreciated.
Thanks all in advance.
When you require('express-edge), it brings in an object. When you register the middleware you need to pass the engine. You have two options...
Access the engine property from the required object
const expressEdge = require('express-edge');
app.use(expressEdge.engine);
Or access the engine property on the require
const expressEdgeEngine = require('express-edge').engine;
app.use(expressEdgeEngine);
https://www.npmjs.com/package/express-edge

I am getting Error in NodeJs NodeMailer with Express Framework

This is My JS code where I want to send an email through Nodemailer. I have added the nodemailer dependency in my package.json but even though I am getting an error in the console.
var express = require('express');
var a = require('mysql');
var app = express();
var bodyParser = require('body-parser');
var randomize = require('randomatic');
var nodemailer = require('nodemailer');
server = require('http').createServer(app);
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'official#gmail.com',
pass: 'admin'
}
});
var mailOptions = {
from: 'official#gmail.com',
to: 'akshay#digiasap.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
server.listen(8999, function (req, res) {
console.log("blockaim Server started !")
});
This is my error console
3|blockaim | SyntaxError: Unexpected token ...
3|blockaim | at exports.runInThisContext (vm.js:53:16)
3|blockaim | at Module._compile (module.js:374:25)
3|blockaim | at Object.Module._extensions..js (module.js:417:10)
3|blockaim | at Module.load (module.js:344:32)
3|blockaim | at Function.Module._load (module.js:301:12)
3|blockaim | at Module.require (module.js:354:17)
3|blockaim | at require (internal/module.js:12:17)
3|blockaim | at Object.<anonymous> (/home/blockaim/node_modules/nodemailer/lib/nodemailer.js:3:16)
3|blockaim | at Module._compile (module.js:410:26)
3|blockaim | at Object.Module._extensions..js (module.js:417:10)

TypeError: Cannot read property 'BSON' of undefined

i'm deploying a nodeJS application with PM2, the process starts fine, but, when i try to access the URL, it stops the process, and then give me an "errored" status. Check the logs and i get this:
TypeError: Cannot read property 'BSON' of undefined
MyExpenses-0 (err): at Object.<anonymous>(/home/develop/development/nodejs/expenses/node_modules/mongodb/lib/mongodb/index.js:46:40)
MyExpenses-0 (err): at Module._compile (module.js:435:26)
MyExpenses-0 (err): at Object.Module._extensions..js (module.js:442:10)
MyExpenses-0 (err): at Module.load (module.js:356:32)
MyExpenses-0 (err): at Function.Module._load (module.js:311:12)
MyExpenses-0 (err): at Function._load (/usr/local/lib/node_modules/pm2/node_modules/pmx/lib/transaction.js:62:21)
MyExpenses-0 (err): at Module.require (module.js:366:17)
MyExpenses-0 (err): at require (module.js:385:17)
MyExpenses-0 (err): at Object.<anonymous> (/home/develop/development/nodejs/expenses/node_modules/mongoose/lib/utils.js:5:16)
MyExpenses-0 (err): at Module._compile (module.js:435:26)
I'm using mongoose for db.
Any clue on this?
Thanks!
UPDATE:
// server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// Database configuration
var db = require('./config/db');
// Connetion port
var port = process.env.PORT || 3500;
// Connect to our mongo db
mongoose.connect(db.url);
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
// Setting router file
require('./app/routes')(app);
// Start app on PORT
app.listen(port);
console.log('Server listening...');
exports = module.exports = app;
My only API url is this:
app.post('/api/expenses/create/', function (req, res) {
var name = req.body.name;
var amount = req.body.amount;
var userId = req.body.userId;
User.findOne({'_id': userId}, function (err, user) {
if (!err) {
var newExpense = Expense({
name: name,
amount: amount,
user_id: userId
});
newExpense.save(function (expenseErr) {
if (!expenseErr) {
res.status(200).json({'message': 'Gasto creado correctamente.', expense: newExpense});
} else {
res.status(400).json({'message': expenseErr});
}
});
} else {
res.status(400).json({'message': 'El usuario seleccionado no existe.'});
}
});
});

Node.js file server on Rpi3 Jesse

I have a file server that works perfectly on my Rpi 2 with Raspian and I have been trying to migrate it to a newer Rpi3 with Jesse. Every time I try to run it I get the following error stack
/media/pi/DemoServer.js:82
server.listen(port, () => {
^
SyntaxError: Unexpected token )
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
Any suggestions on why this is occurring? Is there a subtle nuance between the two distributions that I should address?
Here is the code for the server (with some omissions).
const express = require('express');
const formidable = require('formidable');
const fs = require('fs-extra');
const http = require('http');
const util = require('util');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
const path = require('path');
const server = express();
const port = process.env.PORT || 1001;
const dirToServe = '/media/pi/Shared';
function setHeaders(res, filepath) {
res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(filepath));
}
server.post('/media/pi/Shared', function(req,res) {
});
//Serve the static folder and the index of the folder
server.use('/', serveIndex(dirToServe, { icond: true }));
server.use('/', serveStatic(dirToServe, {setHeaders: setHeaders }));
server.listen(port, () => {
console.log('listening on port ' + port);
});

Categories

Resources