Modules in Node.js - javascript

I am trying to understand how to use modules in node.js to organize my code. Here are my two files 1. server.js 2. index.js
server.js
var http = require("http");
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
exports.start = function () {
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
index.js
var server = require('./server.js').inspect;
server.start();
But when i execute
node index.js
I get this following error.
ashwin#ashwin-vm:~/winshare/node-tut1$ node index.js
/home/ashwin/winshare/node-tut1/index.js:3
server.start();
^
TypeError: Cannot call method 'start' of undefined
at Object.<anonymous> (/home/ashwin/winshare/node-tut1/index.js:3:8)
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)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
ashwin#ashwin-vm:~/winshare/node-tut1$
Here are my node and Ubuntu versions
ashwin#ashwin-vm:~/winshare/node-tut1$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 13.10
Release: 13.10
Codename: saucy
ashwin#ashwin-vm:~/winshare/node-tut1$
ashwin#ashwin-vm:~/winshare/node-tut1$ node --version
v0.10.25

Remove the .inspect from this line:
var server = require('./server.js').inspect;

Related

node.js cannot find 'neo4j' module (Thingdom)

After many tries, I am unnable to connect node.js to Neo4j installed in my computer. I am able to access both separately, and both work fine. I have install in my Node.js directory the Thingdom ('neo4j') module in the directory, but when require('neo4j') prints an error.
Image of my Node.js folder with Neo4j installed in modules
var neo4j = require("neo4j");
var db = new neo4j.GraphDatabase("http://localhost:7474");
var node = db.createNode({hello: 'world'}); // instantaneous, but...
node.save(function (err, node) { // ...this is what actually persists.
if (err) {
console.error('Error saving new node to database:', err);
} else {
console.log('Node saved to database with id:', node.id);
}
});
And when using in the cmd: "node index.js" it throws me this error:
C:\Users\RRamos\Documents\Projects\test-neo4j>node index.js
module.js:341
throw err;
^
Error: Cannot find module 'neo4j'
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> (C:\Users\RRamos\Documents\Projects\test-neo4j\index.js:1:75)
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 Function.Module.runMain (module.js:447:10)
I got the same problem. As there's no solution in this post, I just add mine.
After running $ npm init and $ npm install --save neo4j-driver, I copy and paste the neo4j example code in index.js:
var neo4j = require("neo4j");
var db = new neo4j.GraphDatabase('http://neo4j:<password>#localhost:7474');
And then I got the same error when running $ node index.js.
In my package.json, I found:
"dependencies": {
"neo4j-driver": "^1.1.0-M02"
}
It's neo4j-driver not neo4j. So replace it in index.js:
var neo4j = require("neo4j-driver");
var db = new neo4j.GraphDatabase('http://neo4j:<password>#localhost:7474');
Now you will get rid of the Cannot find module 'neo4j' error!
In addition, if you use the 1.1.0 version of neo4j-driver(for Neo4j 3.0.0+), you may get this error:
var db = new neo4j.GraphDatabase('http://neo4j:<password>#localhost:7474');
^
TypeError: neo4j.GraphDatabase is not a constructor
at Object.<anonymous> (D:\Codes\neo4j_test\server.js:2:10)
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)
at run (bootstrap_node.js:352:7)
at startup (bootstrap_node.js:144:9)
at bootstrap_node.js:467:3
It seems neo4j.GraphDatabase is only available in older version of neo4j-driver.
Here's the up-to-date tutorial of neo4j-driver.
Use the following code instead:
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "<password>"));
// Create a session to run Cypher statements in.
// Note: Always make sure to close sessions when you are done using them!
var session = driver.session();
// Run a Cypher statement, reading the result in a streaming manner as records arrive:
session
.run("MERGE (alice:Person {name : {nameParam} }) RETURN alice.name", { nameParam:'Alice' })
.subscribe({
onNext: function(record) {
console.log(record._fields);
},
onCompleted: function() {
// Completed!
session.close();
},
onError: function(error) {
console.log(error);
}
});

Error: Not running on server.close()

I have an error Not running only when I start my app.js on my server, it works on localhost.
My code is there : Github
Error: Not running
at Server.close (net.js:1233:11)
at Object.<anonymous> (/home/Nahis_Wayard/summoner-infos/app.js:13:10)
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)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
Edit: I remove the 'server.close()' and now it works everywhere
Thanks for your help !
In your app.js, this code var server = http.createServer(app); is used.
However, the http.createServer() is async function, it returns a new instance of http.Server, and http.server inherits from net.Server and has the additional events.
So call server.close() could cause the error Error: Not running in your case.
Here is one sample codes shown the close() is invoked.
var server = http.createServer( (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
server.listen(1337, '127.0.0.1', () => {
// other operations here
server.close();
});

Unexpected token: io.listen(server)

I am new to node.js. Following some of the tutorials, I created a file named server.js and put this code in that file:
var http = require("http");
var url = require('url');
var fs = require('fs');
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
console.log(path);
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '/socket.html':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('Inside hello world');
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 403");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 405");
break;
}
response.end();
});
server.listen(8001);
var io.listen(server);
Then I run this using the command: node C:\Users\user\Desktop\server.js and I get this error:
C:\Users\user\Desktop\server.js:38
var io.listen(server);
^
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
This line is causing the error:
var io.listen(server);
Initially I thought of installing the npm package socket.io hence I tried this:
npm install --save socket.io
But after this also I am getting the same error:
C:\Users\user\Desktop\server.js:38
var io.listen(server);
^
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
Please advice how to resolve this error.
The var keyword is used to declare a variable. I suspect you're missing the variable name:
var foo = io.listen(server);
Other that that, there's no io anywhere else in your code. Are you missing a require call?
The socket.io library is apparently not bundled:
C:\>node
> require("socket.io");
Error: Cannot find module 'socket.io'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at repl:1:1
at REPLServer.self.eval (repl.js:110:21)
at repl.js:249:20
at REPLServer.self.eval (repl.js:122:7)
at Interface.<anonymous> (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
Installation though is a one liner:
npm install socket.io
var io.listen(server);
By using the keyword var it expects an assignment statement or declaration, and you're trying to use a method call as a variable name basically.
As for removing it, you'll get a io is not defined error because it looks like you're not calling the module.
var io = require("socket.io");

Node.js Express JS - Could not find module

Ive allready read 3-4 topics on this here at stackoverflow, but i simply cant seem to run my node.
I Try to run:
node app.js local
and it returns:
Error: Cannot find module './config'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/larsfalcon/Documents/lkrieger/git/testinggrounds/app.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)
at Function.Module.runMain (module.js:497:10)
Before i run this command i do:
npm i
And it installs my packages, i can physicaly see in my node_modules that express is there, but even if i try run express in the CLI it says its not a bash so i assume its not installed somehow still?
here is a review of my 2 app.js and index.js files that i need to run my node.
App.js
var config = require('./config')();
http.createServer(app).listen(config.port, function(){
console.log('Express server listening on port ' + config.port);
});
index.js
var config = {
local: {
mode: 'local',
port: 3000
},
staging: {
mode: 'staging',
port: 4000
},
production: {
mode: 'production',
port: 5000
}
}
module.exports = function(mode) {
return config[mode || process.argv[2] || 'local'] || config.local;
}
What should i do?
So that means that there is no config.js in the same folder as the app.js.
UPDATE: you'll want require('./config/config').

node.js + express error: Cannot read property 'handle' of undefined

I am new to node.js. I was trying a script which is using express module.
I have installed express, using,
npn install express
When I run the code I got the error
TypeError: Cannot read property 'handle' of undefined
at Function.app.use (c:\node_modules\express\lib\application.js:113:9)
at Object.<anonymous> (c:\node\uploadResize.js:13:6)
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)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
How to solve this issue?
Here is my node script.
var http = require('http'), // Libraries
util = require('util'),
fs = require('fs'),
couch = require('cradle'),
connect = require('express'),
endsWith, // Internal Functions
determineMimeType,
upload;
connect()
.use(connect.bodyParser())
.use(upload)
.listen(3000);
upload = function (req, res, next) {
// function body
}
You need to assign upload a value before passing it to app.use
Use something like this:
var app = express();
app.configure(function() {
var hourMs = 1000*60*60;
app.use(express.static('c:\\node', { maxAge: hourMs }));
app.use(express.directory('c:\\node'));
app.use(express.errorHandler());
});
the code not is npm install express ??
then the dir node_modules in the same dir in witch you have your app
C:\node\node_modules
C:\node\app.js

Categories

Resources