NodeJS: Error: Cannot find module '/models/filename' after having renamed it - node.js

I am still relatively new to NodeJS. Now I encounter this problem: I had a file called "./models/route" I renamed it by changing the filename in VS Code to: "./models/routes". I then changed that name in all of the scripts. I checked, doubledchecked, triplechecked and quadruplechecked that it has been changed everywhere and it has.
Now I get this error in the console:
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module './models/routes'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\node-projects\wandelverhalen\controllers\routesController.js:4:16)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\node-projects\wandelverhalen\index.js:11:26)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
[nodemon] app crashed - waiting for file changes before starting..
The error apparently is encountered in internal/modules/cjs/loader.js:638. So it does not point me to a script that I made or can change.
I really am at a loss...
Edit:
As Mosifa points out in his comment the error points to ./wandelverhalen/controllers/routesController.js and ./wandelverhalen/index.js.
Here are the scripts. I still can't find the problem.
index.js:
"use strict";
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const Routes = require("./models/routes");
const homeController = require("./controllers/homeController");
// const errorController = require("./controllers/errorController");
const routesController = require("./controllers/routesController");
mongoose.connect("mongodb://localhost:27017/db_wandelen", {
useNewUrlParser: true
});
const db = mongoose.connection;
db.once("open", () => {
console.log("Connected to MongoDB");
});
app
.set("port", process.env.PORT || 3000)
.set("view engine", "ejs")
.use(
express.urlencoded({
extended: false
})
)
.use(express.json())
.use(express.static("static"))
.use(layouts)
.use((req, res, next) => {
console.log(`Request made to ${req.url}`);
next();
})
// .use(errorController.pageNotFoundError)
// .use(errorController.internalServerError)
.get("/", homeController.start)
.get("/kempen", homeController.kempen)
.get("/rivieren", homeController.rivieren)
.get("/oost_belgie", homeController.oost_belgie)
.listen(app.get("port"), () => {
console.log(`Server running at port ${app.get("port")}`);
});
routesController.js:
"use strict";
const mongoose = require("mongoose");
const Routes = require("./models/routes");
exports.getAllRoutes = (req, res, next) => {
Routes.find({}, (error, routes) => {
if (error) next(error);
req.data = routes;
next();
});
};

Related

Cannot find module nodeJS

Hello I'm having a silly problem but I can't find the solution. When I try start my localhost I get an error saying this :
Error: Cannot find module 'passport'
Require stack:
- D:\Other\Projects\Code\Powershell\shopping-cart\config\passport.js
- D:\Other\Projects\Code\Powershell\shopping-cart\routes\index.js
- D:\Other\Projects\Code\Powershell\shopping-cart\app.js
- D:\Other\Projects\Code\Powershell\shopping-cart\bin\www
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:982:15)
at Function.Module._load (internal/modules/cjs/loader.js:864:27)
at Module.require (internal/modules/cjs/loader.js:1044:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\config\passport.js:1:16)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Module.require (internal/modules/cjs/loader.js:1044:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\routes\index.js:5:16)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'D:\\Other\\Projects\\Code\\Powershell\\shopping-cart\\config\\passport.js',
'D:\\Other\\Projects\\Code\\Powershell\\shopping-cart\\routes\\index.js',
'D:\\Other\\Projects\\Code\\Powershell\\shopping-cart\\app.js',
'D:\\Other\\Projects\\Code\\Powershell\\shopping-cart\\bin\\www'
}
I understand that it is not finding the passport.js file, I have checked the path name more than 10 times and I saw another problem where the guy had not installed the passport module, so I did that as well but it is still throwing the same error. This is what my index.js looks like :
var express = require('express');
var router = express.Router();
var Product = require('D:/Other/Projects/Code/Powershell/shopping-cart/models/product');
var csrf = require('csurf');
var passport = require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');
var csrfProtection = csrf();
router.use(csrfProtection);
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find(function(err, docs) {
var productChunks = [];
var chunkSize = 3;
for (var i = 0; i < docs.length; i += chunkSize) {
productChunks.push(docs.slice(i, i + chunkSize));
}
res.render('shop/index', { title: 'Shopping Cart', products: productChunks });
});
});
router.get('/user/signup', function (req, res, next) {
res.render('user/signup', {csrfToken: req.csrfToken()});
});
router.post('/user/signup', passport.authenticate('local.signup', {
successRedirect: '/user/profile',
failureRedirect: '/user/signup',
failureFlash: true
}));
router.get('/user/profile', function(req, res, next) {
res.render('user/profile');
});
module.exports = router;
Any help would be appreciated, thanks! Also , I have another problem , can I post another question in like one hour? (is it allowed to have more than 1 questions posted?)

module.js:549 throw err;

> module.js:549
> throw err;
> ^
>
> Error: Cannot find module '..models/category'
> at Function.Module._resolveFilename (module.js:547:15)
> at Function.Module._load (module.js:474:25)
> at Module.require (module.js:596:17)
> at require (internal/module.js:11:18)
> at Object.<anonymous> (/home/mridul/shafee-it/routes/admin.js:2:18)
> at Module._compile (module.js:652:30)
> at Object.Module._extensions..js (module.js:663:10)
> at Module.load (module.js:565:32)
> at tryModuleLoad (module.js:505:12)
> at Function.Module._load (module.js:497:3)
> at Module.require (module.js:596:17)
> at require (internal/module.js:11:18)
> at Object.<anonymous> (/home/mridul/shafee-it/server.js:74:21)
> at Module._compile (module.js:652:30)
> at Object.Module._extensions..js (module.js:663:10)
> at Module.load (module.js:565:32) [nodemon] app crashed - waiting for file changes before starting...
Here is my ..models/category(category schema)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
name: { type: String, unique: true, uppercase: true}
});
module.exports = mongoose.model('Category', CategorySchema);
add-category Route in admin.js file
const router = require('express').Router();
const Category = require('..models/category');
// add-category route
router.get('/add-category', function(req, res, next) {
res.render('admin/add-category', { message: req.flash('success') });
});
router.post('/add-category', function(req, res, next) {
var category = new Category();
category.name = req.body.name;
category.save(function(err) {
if (err) return next(err);
req.flash('success', 'Successfully added a category');
return res.redirect('/add-category');
});
});
Here also server.js file to include the category
const Category = require('./models/category');
app.use(function(req, res, next) {
Category.find({}, function(err, categories) {
if (err) return next(err);
res.locals.categories = categories;
next();
});
});
const adminRoutes = require('./routes/admin');
app.use(adminRoutes);
when i run my server or route the add-category url then show module.js:549 throw err; this problem.
Here is my problem details and i check my code different times.
Then how can i solve this problem.
Seems to me that you forgot a /:
require('..models/category');
require('../models/category');
This is why ..models/category throws an error. From a general point of view, when require can't find a local module, don't "check the code", just check where the file is, and what path you wrote, it's always one or the other. ;)

ActiveDirectory Authentication using NODE for Windows SQL 2012

Am using node Active directory for validating users. Here is my node code:
const express = require('express');
const async = require('async');
const activedirectory = require('activedirectory');
var underscore = require('underscore');
const ldap = require('ldapjs');
const bunyan = require('bunyan');
const app = express();
app.get('/',(req,res) => {
var config = { url: 'ldap://10.100.1.10',
baseDN: 'dc=HBCAudit,dc=COM',
username: 'traveldesk.dev',
password: '$oftvision#123' }
var ad = new activedirectory(config);
});
//Port Number
const port = 7000;
//CORS Middleware
app.use(cors());
//Start Server
app.listen(port, () =>{
console.log('Server started on port '+ port);
});
But am getting error in command prompt like this:
c:\spitravel>node app.js
module.js:471
throw err;
^
Error: Cannot find module 'once'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (c:\spitravel\node_modules\ldapjs\lib\client\client.js
:8:12)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
I don't know why am getting this error. Am new to NODEJS.
Its due to depencies of ldapjs module, please run npm install ldapjs and recheck

Auto increment field in mongoose

Im trying to create auto increment field in mongoose but i cant create for some reason
This is my app.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Artist = require('./models/artist');
mongoose.connect('mongodb://localhost/auto-increment');
app.get('/', function(req, res){
Artist.create({
name: "artistName",
fpimage: "Cover"
}, function(err, artist){
if(err) {
console.log(err);
} else {
artist.save();
console.log(artist);
res.send('Hi ')
}
});
});
// Set Port
app.set('port', (process.env.PORT || 3000));
// Run Server
app.listen(app.get('port'), function(){
console.log('Server has started on Port: '+app.get('port'));
});
and this is my artist model
var mongoose = require("mongoose");
var autoIncrement = require('mongoose-auto-increment');
var artistSchema = new mongoose.Schema({
name: String,
fpimage: String
});
artistSchema.plugin(autoIncrement, 'Artist');
module.exports = mongoose.model('Artist', artistSchema);
When i run the app, i get following the error message
fn(this, opts);
^
TypeError: fn is not a function
at Schema.plugin (C:\Users\tjesu\Desktop\pidal\auto-increment\node_modules\mongoose\lib\schema.js:1060:3)
at Object.<anonymous> (C:\Users\tjesu\Desktop\pidal\auto-increment\models\artist.js:10:14)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\tjesu\Desktop\pidal\auto-increment\app.js:4:14)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
How can i fix this error? What should i do?
From the docs, it looks like you're missing two things:
You need to initialize autoIncrement:
autoIncrement.initialize(mongoose.connection);
You need to change your call to:
artistSchema.plugin(autoIncrement.plugin, 'Artist');
use autoIncrement.plugin instead of autoIncrement in your model
like:
artistSchema.plugin(autoIncrement.plugin, 'Artist');
and need initialize autoIncrement once
var connection = mongoose.createConnection("mongodb://localhost/auto-increment");
autoIncrement.initialize(connection);
and can use get like
app.get('/', function(req, res){
var artist = new Artist({name: "Telmuun",fpimage: "Cover"});
artist.save(function(err, saved) {
if(err) {
console.log(err);
}
else {
res.send('saved');
}
});
});

Nodejs not able to run when i move the routes and model to different folders

I am trying to run the serverjs in nodejs by separating the routes and models in different folders, but I am getting the below mentioned error where as i can run the same without moving them to different folders.
Error: Cannot find module '../models/catModel'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (/home/rajesh/app4/routes/catRoute.js:2:10)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (/home/rajesh/app4/cat_server.js:14:12)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
Source Code:
/app4/cat_server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/cats');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var cats = require('../routes/catRoute')(app);
var server = app.listen(3000, function(){ console.log('Sever runnign at localhost:3000'); });
/app4/routes/catRoute.js
var _= require('lodash');
var Cat= require('../models/catModel');
module.exports = function(app) {
/*Create*/
app.post('/cat', function(req, res){
var newCat = new Cat(req.body);
newCat.save(function(err){
if(err){ res.json({info: "error during creating of cat create", error:err}); };
res.json({info: 'Cat created successfully'});
});
});
}
/app4/models/catModel.js
var mongoose = require('mongoose');
var catSchema = mongoose.Schema({ name: String, age: Number, type: String });
module.exports = mongoose.model('Cat', catSchema);
Something doesn't look right with the relative path loading.
Given that /app4/routes/catRoute.js is being loaded correctly with a path of ../routes/catRoute, I suspect that doing the following will help:
var Cat = require('../../models/catModel');
This error comes when path is not right for server
Try this
var Cat = require(process.cwd() + '/models/catModel');
Its resolved, the issue is with my catModel.js file has an additional extension, once I updated its working as expected. Thanks for all your help.

Resources