Error: Cannot find module on visual studio code (node server.js) - javascript

I'm working on a project and I need to make the node server.js work first before I proceed to check it elsewhere. I am experiencing this error:
Error: Cannot find module 'C:\Users\xxxx\Desktop\xxx\xxxxxxx\xxxxxx\server.js'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:383:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:496:3
here are my codes for server.js
"use strict"
const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes/RouteFood');
var app = express();
var host = "127.0.0.1";
var port = 8080;
var startPage = "home.html";
app.use(express.static('./public'));
app.use(express.static('./public/js'));
app.use(express.static('./public/css'));
app.use(express.static('./public/images'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
routes.routeFood(app);
function gotoIndex(req, res) {
console.log(req.params);
res.sendFile(__dirname + "/" + startPage);
res.sendFile(__dirname + "/" + "food.html");
}
app.get('/food.html', gotoIndex);
var server = app.listen(port, host, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
Can someone help me to solve this? and tell me what the error is?

Related

connecting Neo4j to nodejs error

I am trying to set up neo4j databace to use with javescript code.
When I run my code, I keep getting this
PS C:\Users\futur\Documents\Coding\Neo4j> node app.js body-parser
deprecated undefined extended: provide extended option app.js:21:20
Server has started GET / 304 37.114 ms - - { Neo4jError: getaddrinfo
ENOTFOUND locthost locthost:7687
at captureStacktrace (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\result.js:200:15)
at new Result (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\result.js:73:19)
at Session._run (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\session.js:122:14)
at Session.run (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\session.js:101:19)
at C:\Users\futur\Documents\Coding\Neo4j\app.js:31:4
at Layer.handle [as handle_request] (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\index.js:281:22
code: 'ServiceUnavailable', name: 'Neo4jError' }
Here is what my code looks like
var express = require("express");
var path = require("path");
var logger = require("morgan");
// var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var neo4j = require("neo4j-driver").v1;
var app = express();
//
// <script src="lib/browser/neo4j-web.min.js"></script>
//view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extened: false}));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
var driver = neo4j.driver("bolt://locthost", neo4j.auth.basic("neo4j", "test"));
var session = driver.session();
//home route
app.get('/', function(req, res){
session
.run("MATCH (n) RETURN n")
.then(function(result){
result.records.forEach(function(records){
console.log(records._fields[0]);
});
})
.catch(function(error){
console.log(error);
});
res.render("index");
});
app.listen(3000);
console.log('Server has started');
module.export = app;
What do I need to do?
You may have a typo in your bolt URI.
If your code is running on the same machine as the neo4j server, try changing locthost to localhost.

How to access io.emit() from routes/index? on express 4.15 [duplicate]

This question already has answers here:
express.js 4 and sockets with express router
(6 answers)
Closed 5 years ago.
bin/www.js
var server = http.createServer(app);
io = require('socket.io')(server);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
});
server.listen(port);
here i need to access or send messages or mongoose result via socket.io(i dont know it is possible or not?)
i need to send messages to client from routes/index.js page.
what i tried is,
module.exports.io = io; //(in `bin/www`)
and access thai io in index.js like this
var io=require('../bin/www');
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
});
but it thows some error
io.on('connection', function(client) {
^
TypeError: io.on is not a function....
my need is ,
I want to send dynamic results to client when a route get called or send some mongoose query results to client using socket.io is it possible?
on express 4.15 var server = http.createServer(app); is on bin/www.js
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
/*app.use(function(req, res, next) {
req.headers['if-none-match'] = 'no-match-for-this';
next();
});*/
//app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public'), {
maxAge: '30d',
setHeaders: function (res, path) {
res.setHeader('Cache-Control', 'public, max-age=14770')
}
}));
console.log("PATH"+path.join(__dirname, 'public'));
app.io = require('socket.io')();
app.io.on('connection', function(socket){
// do whatever you want
});
const userRoute = require('./routes/index')(app.io);
app.use('/', userRoute);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Error after update the code given by Ashish
PATHC:\Users\ADSS\Desktop\PrintAdmin\public
C:\Users\ADSS\Desktop\PrintAdmin\node_modules\express\lib\router\index.js:635
return fn.apply(this, arguments);
^
TypeError: Cannot read property 'apply' of undefined
at
C:\Users\ADSS\Desktop\PrintAdmin\node_modules\express\lib\router\index.js:635:14
at next (C:\Users\ADSS\Desktop\PrintAdmin\node_modules\express\lib\router\index.js:210:14)
at Function.handle (C:\Users\ADSS\Desktop\PrintAdmin\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\ADSS\Desktop\PrintAdmin\node_modules\express\lib\router\index.js:47:12)
at Object. (C:\Users\ADSS\Desktop\PrintAdmin\app.js:46:44)
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)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (C:\Users\ADSS\Desktop\PrintAdmin\bin\www:7:11)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
I guess you have generated the app using express generator which creates app.js and bin/www files, There is a circular dependency issue to use io object inside routes. Here's what you can do,
Inside app.js
app.io = require('socket.io')(); // initialize io, attach server in www
// use socket events here
app.io.on('connection', function(socket){
// do whatever you want
})
// you can pass app.io inside the router and emit messages inside route.
const userRoute = require('./routes/user')(app.io);
app.use('/users', userRoute);
Inside bin/www
var io = app.io;
var server = http.createServer(app);
io.attach(server);
Now here's how router looks like, user.js
module.exports = function(io){
router.get('/', function(req, res, next){
io.emit("message", "your message");
res.send();
})
// edited
return router;
}
Note: I havent practically tried it yet.
But Can u try this pattern instead?
In www.js
module.exports = function(io) {
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
});
}
In index.js
var server = http.createServer(app);
io = require('socket.io')(server);
require('./wwww.js)(io);

TypeError : cannot read property 'method' of undefined in nodejs Application

I am developing a simple chat application using node.js and socket.io. When I am connecting to the socket.io then I face an error of "cannot read property 'method' of undefined".
Here is the app.js file code:-
var express = require('express'),
app = express(),
path = require('path')
cookieParser = require('cookie-parser')
session = require('express-session')
config = require('./config/config.js'),
ConnectMongo = require('connect-mongo')(session),
mongoose = require('mongoose').connect(config.dbURL),
passport = require('passport'),
FacebookStrategy = require('passport-facebook').Strategy,
rooms = [] ;
app.set('views', path.join(__dirname , 'views'));
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname,'public')));
app.use(cookieParser());
var env = process.env.NODE_ENV || 'development';
if(env === 'development'){
// dev specific settings
app.use(session({secret:config.sessionSecret, saveUninitialized : true, resave : true}));
} else {
//Production specific settings
app.use(session({
secret : config.sessionSecret,
saveUninitialized : true,
resave : true,
store : new ConnectMongo({
// url : config.dbURL, (for Avoiding two seperate connection)
mongooseConnection:mongoose.connections[0],
stringify : true
})
}));
}
app.use(passport.initialize());
app.use(passport.session());
require('./auth/passportAuth.js')(passport , FacebookStrategy , config , mongoose);
require('./routes/routes.js')(express,app ,passport , config);
/* app.listen (3000 , function(){
console.log("ChatUp working on the Port 3000");
console.log('Mode:'+ env);
}); */
app.set('port', process.env.PORT || 3000);
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
require('./socket/socket.js')(io,rooms);
server.listen(app.get('port' , function(){
console.log('Chat Up on Port : '+ app.get('port'));
}))
And Here is my Chatrooms.html srcipt :-
$(function() {
var host = '{{config.host}}';
var socket = io.connect(host + '/roomlist'); // http://localhost:3000/roomlist
socket.on('connect', function() {
console.log('Connection Established .. !');
})
})
JSON file contain "host":"http://localhost:3000"
But when I run the code there is an error :TypeError : cannot read property 'method' of undefined
Console Error :-
c:\Users\ANKUR SINGH\Desktop\node\Chat App\node_modules\express\lib\router\index.js:138
debug('dispatching %s %s', req.method, req.url);
^
TypeError: Cannot read property 'method' of undefined
at Function.handle (c:\Users\ANKUR SINGH\Desktop\node\Chat App\node_modules\express\lib\router\index.js:138:33)
at EventEmitter.handle (c:\Users\ANKUR SINGH\Desktop\node\Chat App\node_modules\express\lib\application.js:173:10)
at Server.app (c:\Users\ANKUR SINGH\Desktop\node\Chat App\node_modules\express\lib\express.js:38:9)
at Server.g (events.js:260:16)
at emitNone (events.js:67:13)
at Server.emit (events.js:166:7)
at emitListeningNT (net.js:1263:10)
at nextTickCallbackWith1Arg (node.js:444:9)
at process._tickCallback (node.js:366:17)
at Module.runMain [as _onTimeout] (module.js:432:11)
at Timer.listOnTimeout (timers.js:92:15)
How to get rid of this error. ??
Picture of : /router/index.js file :-
Error picture
After 9 hours of continuous struggling. I have the found the solution of my question.
The error code :-
app.set('port', process.env.PORT || 3000 );
server.listen(app.get('port' , function(){
console.log('Chat Up on Port : '+ app.get('port'));
}));
And the Correct code :-
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Updated : Server listening at port %d', port);
});
The reference link is:-
Correct Code reference
Your code would work. There is a missing ')'
app.set('port', process.env.PORT || 3000 );
server.listen(app.get('port') , function(){
console.log('Chat Up on Port : '+ app.get('port'));
});
if you are using app.js as express and start.js as the "npm start", all you have to do is to make sure the application was exported module.exports = app; and on the start.js you just have to require the module require('./app') this works fine.
Aren't you missing some commas when declaring your variables?
path = require('path')
cookieParser = require('cookie-parser')
session = require('express-session')
path = require('path'),
cookieParser = require('cookie-parser'),
session = require('express-session'),

When I run node app.js command it gives me error ` ENOENT, no such file or directory on .mime.types

I have the following script:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var app = express();
var port = 3700;
var request = require('request');
var redis = require('redis');
// Set View Path; Set Engine; Integrate with Express
app.set('views', path.join(__dirname + '/views'));
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);
// Public dir
app.use(express.static(__dirname + './public'))
.use(bodyParser.json())
.use(bodyParser.urlencoded({
extended: true
}));
var routes = require('./routes/index');
app.use('/', routes);
io = require('socket.io').listen(app.listen(port));
console.log("Listening on port " + port);
var wbApp = require('./components/init');
module.exports = app;
The file name is app.js. When i run node app.js command it gives me the following error:
fs.js:500
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT, no such file or directory '/home/user/projects/wbchat/node_modules/express/node_modules/send/node_modules/mime/types/mime.types'
at Error (native)
at Object.fs.openSync (fs.js:500:18)
at Object.fs.readFileSync (fs.js:352:15)
at Mime.load (/home/user/projects/wbchat/node_modules/express/node_modules/send/node_modules/mime/mime.js:54:20)
at Object.<anonymous> (/home/user/projects/wbchat/node_modules/express/node_modules/send/node_modules/mime/mime.js:90:6)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
Could you please help me how can i solve this problem. Also when i am commenting var express = require('express'), the error is gone.
Did you run npm install to install all the dependencies? If you did, I would remove the folder ./npm_modules and run npm install because you might have something corrupted.
Hopefully this would help.

Nodejs / Express - Launching my app: express.createServer() is deprecated

I downloaded a node app to test and play around with. I have googled around and found that Express is found to be a little outdated. Can someone help me to fix the implemented code?
Here is the code
/**
* Module dependencies.
*/
// base dependencies for app
var express = require('express')
, routes = require('./routes')
, DB = require('./accessDB').AccessDB
, passport = require('passport')
, mongoose = require('mongoose')
, mongoStore = require('connect-mongodb');
var app = module.exports = express.createServer();
global.app = app;
var DB = require('./accessDB');
var conn = 'mongodb://localhost/CrowdNotes';
var db;
// SocketIO Configuration
//var io = require('socket.io').listen(app);
//
//io.sockets.on('connection', function(socket) {
// socket.on('user note', function (note) {
// console.log(note);
// });
//});
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(require('stylus').middleware({ src: __dirname + '/public' }));
app.use(express.session({
store: mongoStore(conn)
, secret: 'applecake'
}, function() {
app.use(app.router);
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));
});
db = new DB.startup(conn);
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
require('./routes')(app);
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
And here is the error I receive once running the app via node app
C:\CrowdNotes>node app
Warning: express.createServer() is deprecated, express
applications no longer inherit from http.Server,
please use:
var express = require("express");
var app = express();
C:\CrowdNotes\app.js:63
console.log("Express server listening on port %d in %s mode", app.address().po
^
TypeError: Object function app(req, res){ app.handle(req, res); } has no method
'address'
at Object.<anonymous> (C:\CrowdNotes\app.js:63:67)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
C:\CrowdNotes>
FIXED.
I am now at the point where I register, and go to login using my new 'User' data and receive this error:
ReferenceError: C:\CrowdNotes\views\account.jade:6
4| div#header
5| h2 CrowdNotes
> 6| p Hi, #{currentUser.name.first}!
7|
8| - if (myEvent)
9| p.center My Event: #{myEvent.name}
currentUser is not defined
at eval (eval at <anonymous> (C:\CrowdNotes\node_modules\jade\lib\jade.js:176:8))
at exports.compile (C:\CrowdNotes\node_modules\jade\lib\jade.js:181:12)
at Object.exports.render (C:\CrowdNotes\node_modules\jade\lib\jade.js:216:14)
at View.exports.renderFile [as engine] (C:\CrowdNotes\node_modules\jade\lib\jade.js:243:13)
at View.render (C:\CrowdNotes\node_modules\express\lib\view.js:75:8)
at Function.app.render (C:\CrowdNotes\node_modules\express\lib\application.js:500:10)
at ServerResponse.res.render (C:\CrowdNotes\node_modules\express\lib\response.js:716:7)
at module.exports.getAccount (C:\CrowdNotes\routes\index.js:47:11)
at Promise.module.exports.getMyEvent (C:\CrowdNotes\accessDB.js:54:7)
at Promise.addBack (C:\CrowdNotes\node_modules\mongoose\lib\promise.js:128:8)
I'm wondering if this is some form of syntax error too? Not sure what's gone wrong here as I thought the code all lined up tbh.
I am using the code from here: https://github.com/rockbot/crowdnotes
The solution is given in the error.
Warning: express.createServer() is deprecated, express
applications no longer inherit from http.Server
please use:
var express = require("express");
var app = express();
So you will have to just do this.
var express = require('express')
, http = require('http');
var app = express();
var server = http.createServer(app);
Its can done with this simple program:
var express = require('express');
var app = express();
app.get('/',
function(req,res)
{
res.send("express");
}
);
app.listen(3333);
it works fine.
Another potential solution to this is to install express 2.5.8 as a dependency.
Add to package.json:
{
"name": "authentication"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"express": "2.5.8"
, "jade": ">= 0.26.1"
}
}
and then run
npm install
var express = require('express');
var app = express();
app.listen(your_port_number);
With the newer release of express (express 4.x), you do not need to create server. app.listen internally does that. Refer https://expressjs.com/en/4x/api.html#app.listen
I am already using the following snippet and it is working fine:
var express =require("express");
var http = require("http");
var app = express();
//app routers here
...
var httpServer = http.Server(app);
httpServer.listen({PORT}, function(err){
});

Categories