Error running express with node - javascript

I'm trying to start a very simple server on my Mac so I can access a file from localhost.
I have node and express installed and this is all that it is in my server file.
var express = require('express'),
app = express();
app.use(express.static(__dirname, '/'));
app.listen(8080);
console.log("App listening on port 8080");
When I try to do:
node server
I get this as a response:
/Users/mt_slasher/node_modules/express/node_modules/serve-static/index.js:47
var opts = Object.create(options || null)
^
TypeError: Object prototype may only be an Object or null: /
at Function.create (native)
at Function.serveStatic (/Users/mt_slasher/node_modules/express/node_modules/serve-static/index.js:47:21)
at Object.<anonymous> (/Users/mt_slasher/Desktop/My Projects/Basket/Site/server.js:4:23)
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 Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
I've run this same file on a Windows machine with the same files and had no problem.
After some digging, I found this line seems to be the main culprit:
app.use(express.static(__dirname, '/'));
Can someone tell me what might be happening?

That is because you are passing "/" as second parameter (options)
app.use(express.static(__dirname + '/'));
See serve-static:
function serveStatic(root, options) ...
https://github.com/expressjs/serve-static/blob/master/index.js
Also note that it would be better to use a different directory than your root e.g. express.static(__dirname + '/public') to avoid exposing your root.

express.static is used to define directory where your "static" files reside look at here for more info.
It accepts only a string with the path you want to be static:
So your code should be:
app.use(express.static('/'));
Or
app.use(express.static(__dirname + '/'));
But that doesn't make much sense, imho.
Remove the line or define the real path where your assets files are.

The second parameter you are passing to express.static is incorrect. remove the second parameter.
app.use(express.static(__dirname));

Related

Mammoth not finding any modules

I am trying to create a Word to HTML converter, and I am trying to use Mammoth as a framework. Whenever I run my script, I get:
Internal/modules/cjs/loader.js:983
throw err;
^
Error: Cannot find module 'mammoth'
Require stack:
- C:\Users\magnu\OneDrive\Documents\GitHub\work_app\app.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)
at Function.Module._load (internal/modules/cjs/loader.js:862:27)
at Module.require (internal/modules/cjs/loader.js:1042:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (C:\Users\magnu\OneDrive\Documents\GitHub\work_app\app.js:4:15)
at Module._compile (internal/modules/cjs/loader.js:1156:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'C:\\Users\\magnu\\OneDrive\\Documents\\GitHub\\work_app\\app.js' ]
}
This is the code for my app.js
// Requirements
var express = require('express'),
ejs = require('ejs'),
mammoth = require('mammoth')
var app = express();
app.set('view engine', 'ejs');
// Mammoth
mammoth.convertToHtml({path: "../../../../Downloads/Federal Gov't - Debate Sheet.docx"})
.then(function(result){
var html = result.value; // The generated HTML
var messages = result.messages; // Any messages, such as warnings during conversion
})
.done();
app.get('/', function (req, res) {
res.render('landing');
})
app.listen(4009, function () {
console.log("Server ready on PORT 4009");
})
If anyone knows the solution to my problem, please post below.
For all of my code, go to Github
The answer to this is very simple. Just make sure you have installed the package.
But I am sure I have already installed the package. What now?
My next course of action is to make sure you have it under dependencies in the package.json file you store other dependencies in. To automate this process, create a GitHub page and start commiting to it. This can speed up your development process by months simply because other people are able to help you.
If those don't work, ask a question and comment it to me and I might be able to help!

cannot find module at function_module 469:15

I am learning nodejs from Courseera and wanted to run a code from command prompt in windows 10.But this error Cannot find module always occurs.Iam completely at aloss what this means.
I have tried all the methods given in the other stack overflow threads but couldn't solve the issue.
node and npm are correctly installed with versions v6.9.2 and 3.10.9 respectively.
D:\shaury\node-http\public>node -v
v6.9.2
D:\shaury\node-http\public>npm -v
3.10.9
This is the problem which is occcuring:
D:\shaury\node-http\public>node serve
module.js:471
throw err;
^
Error: Cannot find module 'D:\shaury\node-http\public\serve'
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:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
There's a typo in your code.
var http = require('http');
var hostname = 'localhost';
var port = 3000;
var server = http.createServer(function(req, res){
console.log(req.headers);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<html><body><h1>Hello World</h1></body></html>');
});
//here you should surround your string in 'quotation marks' but make sure to use `backticks`
server.listen(port, hostname, function(){
console.log(`Server running at http://${hostname}:${port}/`);
});
Edit: actually you might need to check that you are in the correct directory. When you launch your app it should be from the directory that your .js file is or else supply the path.

Node 101: app.use ReferenceError [route] not defined

I am new to Node/Express, and have a basic question about routing as I am getting the following error message:
app.use('/edu', edu);
^
ReferenceError: edu is not defined
at Object.<anonymous> (/Users/ronitelman/Dropbox/happy/happy/app.js:29:17)
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)
at require (module.js:384:17)
at Object.<anonymous> (/Users/ronitelman/Dropbox/happy/happy/bin/www:7:11)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
[nodemon] app crashed - waiting for file changes before starting...
app.js:
app.use('/', routes);
app.use('/users', users);
app.use('/about', about);
app.use('/edu', edu);
File structure:
> root
> ...
> routes
| about.js
| edu.js
| index.js
| users.js
edu.js:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('dashboard', { layout: 'layout_edu' });
});
module.exports = router;
Additionally, I wanted to know if I should use the 'extends layout' in my dashboard.jade file, or if I should define the layout in the route
dashboard.jade
extends layout //- or res.render('dashboard', { layout: 'layout_edu' }); ?
block content
include ./nav/nav_layout.jade
.wrapper
include ./home/home.jade
include ./home/benefits.jade
include ./home/students.jade
include ./home/teachers.jade
include ./home/admin.jade
include ./home/analytics.jade
include ./home/tech.jade
include ./home/featured.jade
Make sure you require your edu module in your app.js file. Usually at the top of the file you would need something like var edu = require('./routes/edu.js'); (which asks node to load your edu.js file in the routes directory).
Concerning your second question, the way you make your extends call in your Jade file should be OK. For more clarity and to avoid mistakes, you should reference it by its filename, like extends ./layout.jade (if layout.jade is in the same directory as dashboard.jade)

socket.io client side in node js

Am I doing something wrong? When I run node client.js. I am getting this error message:
/web/ws/node_modules/socket.io/node_modules/engine.io/lib/server.js:358
var listeners = server.listeners('request').slice(0);
^
TypeError: Object http://localhost:8080 has no method 'listeners'
at Server.attach (/web/ws/node_modules/socket.io/node_modules/engine.io/lib/server.js:358:26)
at Function.attach (/web/ws/node_modules/socket.io/node_modules/engine.io/lib/engine.io.js:124:10)
at Server.listen.Server.attach (/web/ws/node_modules/socket.io/lib/index.js:226:21)
at new Server (/web/ws/node_modules/socket.io/lib/index.js:51:17)
at Server (/web/ws/node_modules/socket.io/lib/index.js:39:41)
at Object.<anonymous> (/web/ws/client.js:2:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
Here is my code:
var io = require('socket.io');
var socket = io('ws://localhost:8080');
socket.on('connect', function () {
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
Please suggest something. where I am doing the mistake ?
The problem here is that you are trying to use socket.io package which is for configuring the server.
Instead you need to use socket.io-client package to be able to act as a client.
You can find usage examples by following provided links.

How to Create DB in Node Js Express Jade JavaScript App

UPDATED
I have researched this a lot further. The web application is using the node-db-migrate package. There is a migration folder with two migrations (with table creations). Since I just git cloned it down I am sure I need to run this and I do have node-db-migrate installed on my machine when I hit npm-list.
I head into this folder and hit db-migrate-up and tried db-migrate-up [filename] but I am getting -bash: db: command not found.
I am using this with the node-postgres package. It should be loading the database.json file according to the node-db-migrate file.
Hi in my data.coffee here is line 1 to 17 as requested, according to the command line it could be the data part that is having problem.
uuid = require 'node-uuid'
fs = require 'fs'
_ = require 'underscore'
moment = require 'moment-timezone'
apis = require '../logic/apis'
q = require 'q'
data = (_.chain fs.readdirSync "data")
.map (filename) ->
"data/" + filename
.map (f) ->
fs.readFileSync f, "utf8"
.map (p) ->
JSON.parse p
.sortBy (json) ->
-json.intlFormatDateTime
.value()
Hi I come from a ruby/rails/sinatra background. I just inherited a javascript web app and I will be rewriting the back end.
I am just trying to start the app locally for now
I did
coffee app.coffee -n
but I am getting the error below.
Error: ENOENT, no such file or directory 'data'
at Object.fs.readdirSync (fs.js:654:18)
at Object.<anonymous> (/Users/judyngai/Desktop/twiage/twiagemed/nodejs/routes/data.coffee:8:17, <js>:16:22)
at Object.<anonymous> (/Users/judyngai/Desktop/twiage/twiagemed/nodejs/routes/data.coffee:1:1, <js>:226:4)
at Module._compile (module.js:456:26)
at Object.loadFile (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:182:19)
at Module.load (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:211:36)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/judyngai/Desktop/twiage/twiagemed/nodejs/app.coffee:3:8, <js>:8:10)
at Object.<anonymous> (/Users/judyngai/Desktop/twiage/twiagemed/nodejs/app.coffee:1:1, <js>:76:4)
at Module._compile (module.js:456:26)
In the app.coffee file there is these three lines of code
express = require 'express'
routes = require './routes'
data = require './routes/data'
I have installed all the dependencies within the package.json file but there is a database.json file with this line attached
{ "dev": "postgres://twiage_db_user:twiage_db_password#localhost/twiage_db" }
how do I create this database? normally in rails its a rake db:create. I feel like this can solve the problem.
It tries to read "data" directory which is missing. Does cwd + ./data/ exist? Also, it's common to use path relative to script with __dirname variable:
dataDir = __dirname + "/data"
data = (_.chain fs.readdirSync dataDir)
.map (filename) ->
dataDir + "/" + filename
.map (f) ->
fs.readFileSync f, "utf8"
.map (p) ->
JSON.parse p
.sortBy (json) ->
-json.intlFormatDateTime
.value()

Categories