NodeJS - no such file or directory, scandir '/static/reports/' - node.js

I tried following this stackoverflow post to try and see my folder on my static webpage but no luck:https://stackoverflow.com/a/31274417
Here is my code:
const express = require('express');
const app = express();
const db = require('./persistence');
var fs = require('fs');
var files = fs.readdirSync('./static/reports');
app.use(require('body-parser').json());
app.use(express.static(__dirname + '/static'));
db.init().then(() => {
app.listen(3000, () => console.log('Listening on port 3000'));
}).catch((err) => {
console.error(err);
process.exit(1);
});
const gracefulShutdown = () => {
db.teardown()
.catch(() => {})
.then(() => process.exit());
};
process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
process.on('SIGUSR2', gracefulShutdown); // Sent by nodemon
Here is a picture of what it looks like from vscode:
Here is a picture of the error from docker:
Here is the error from text:
internal/fs/utils.js:269
throw err;
^
Error: ENOENT: no such file or directory, scandir './static/reports'
at Object.readdirSync (fs.js:955:3)
at Object.<anonymous> (/app/src/index.js:5:16)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47 {
errno: -2,
syscall: 'scandir',
code: 'ENOENT',
path: './static/reports'
}

Starting a file path with a / denotes that it's at the root of the filesystem. Don't use a /; instead, just use static/reports. You can also use ./static/reports if the code will be run from the src/ directory every time.
var fs = require('fs');
var files = fs.readdirSync('static/reports/');

Related

nodemon app crashed - waiting for file changes before starting ... Error

appjs
const express = require("express");
const path = require("path");
const homeRouter = require("./routes/home.routes");
const app = express();
const port = 8000;
app.use(express.static(path.join(__dirname, "assets")));
app.use(express.static(path.join(__dirname, "images")));
app.set("view engine", "ejs");
app.set("views", "views");
app.use("/", homeRouter);
app.listen(port, () => {
console.log(`server listen on port ${port}`);
});
home routes
const router = require('express').Router()
const homeController = require('../controllers/home.controller')
router.get('/', homeController.getHome)
module.exports = router
homecontroller
const productsModel = require('../models/products.models')
exports.getHome = (req,res,next) => {
//get products
//get render index.ejs
productsModel.getAllproducts().then(products => {
res.render('index', {
products: products
})
})
}
products.models
const mongoose = require("mongoose");
const DB_URL = 'mongodb://localhost:27017/shop'
const productsSchema = mongoose.Schema({
name:String,
image:String,
price:String,
category:String,
description:String
})
const product = mongoose.model('product', productsSchema)
exports.getAllproducts = () => {
//connect to db
//get products
//disconnect
return new Promise((resolve,reject) => {
mongoose.connect(DB_URL).then(() => {
return product.find({})
}).then(products => {
mongoose.disconnect()
resolve(products)
}).catch(err => reject(err))
})
}
Error
node:events:504
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::8000
at Server.setupListenHandle [as _listen2] (node:net:1330:16)
at listenInCluster (node:net:1378:12)
at Server.listen (node:net:1465:7)
at Function.listen (C:\Users\islam\OneDrive\Desktop\shopnode\node_modules\express\lib\application.js:635:24)
at Object. (C:\Users\islam\OneDrive\Desktop\shopnode\app.js:17:5)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) Emitted 'error' event on Server
instance at:
at emitErrorNT (node:net:1357:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) { code: 'EADDRINUSE',
errno: -4091, syscall: 'listen', address: '::', port: 8000 }
[nodemon] app crashed - waiting for file changes before starting...
In case we have some project running are both same port and on your server then catch this error and i have solve in that time.
open terminal set your Dir location and run this command on your terminal
doing this things
using this command :- pkill node
or
for mac :- sudo killall -9 node
or
for windows :- > killall -9 node
or
killall node
otherwise use this on your defined port modify your code
var port = process.env.PORT || 8000;
do all this things then server restart
npm start or node app.js

How to fix node:internal/modules/cjs/loader:936?

I followed a node.js tutorial online and I got this error when I runned the script.
node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module 'C:\Users\sem20\Downloads\testing\API\cmusic-api\index.js' at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:17:47 { code: 'MODULE_NOT_FOUND', requireStack: [] }
I installed every package I needed
Here is the index.js
const express = require('express')
const axios = require('axios')
const cheerio = require('cheerio')
const app = express()
app.listen(PORT, () => console.log(`Listening on port ${PORT}`))
Can somebody help me fix this?
I installed every package I needed

NodeJS: Error: Cannot find module '/models/filename' after having renamed it

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

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

`npm` error as `Error: Cannot find module` - how to fix

In my application, when i try to call the service I am getting the error as like this:
module.js:327
throw err;
^
Error: Cannot find module '/api/sessions'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\Tutorials\try\ModernWebApp\server.js:13:9)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
[14:38:53] [nodemon] app crashed - waiting for file changes before starting...
here is my server.js file:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static( __dirname + '/assets'))
app.use(express.static( __dirname + '/templates'))
app.use(bodyParser.json());
//if i remove both this 2 lines, no issues come.
app.use(require('/api/sessions', require( __dirname + '/controllers/api/sessions')));
app.use(require('/api/users', require('./controllers/api/users')));
app.get('/', function( req, res ){
res.sendFile( __dirname + '/layouts/app.html');
})
app.listen( 8888, function(){
console.log('app listening!' + 8888 );
})
what is wrong here, how to solve this. the 2 files are nothing but to handling the query from front end.
session.js for sample:
var router = require('express').Router();
var bcrypt = require('bcryptjs');
var jwt = require('jwt-simple');
var User = require('../../models/user');
var config = require('../../config');
router.post('/sessions', function( req, res, next ) {
User.findOne({
username: req.body.username,
}).select('password').select('username')
.exec(function( err, user ) {
if( err ) { return next( err )}
if(!user) { return res.send(401)}
bcrypt.compare(req.body.password, user.password, function( err, valid ) {
if( err ) { return next( err )}
if(!valid) { return res.send(401)}
var token = jwt.encode({username:user.username}, config.secret);
res.send( token );
})
})
});
module.exports = router;
try using just.
app.use(require('/api/sessions'));
app.use(require('/api/users'));
If that doesn't work give the proper path of the module you want to require.Because require function only take one parameter that is a module ID in string.
https://nodejs.org/api/modules.html#modules_module_require_id
you just use require('/api/sessions'), so node will look for sessions.js file in your root dir(/) not your work directory.
maybe you should try require('./api/sessions')

Resources