Error: Not running on server.close() - javascript

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

Related

Node.js async await in express

I'm building an endpoint /users which will return the contents in the Users.json file. I'm using aysnc/await feature.
var express = require('express');
var app = express();
var fs = require('fs');
var readFile = Promise.promisify(fs.readFile);
const util = require('util');
app.get('/users', async (req, res, next) => {
try {
const user = await readFile('./users.json');
return eval(user);
//res.send(JSON.parse(data));
// res.json(user);
} catch (e) {
//this will eventually be handled by your error handling middleware
next(e)
}
});
app.listen(3000,function(){
console.log("listening on port 3000");
});
This throws the below error
SyntaxError: Unexpected token (
at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28) 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.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at
startup (bootstrap_node.js:149:9)
I'm using the npm 3.10.10 with node v6.11.3.
Can someone please guide where I have gone wrong?
Async/await is only available in Node versions 8 an up. Try using a newer Node version if possible.
Instead of calling:
return eval(user);
You should call:
res.send(JSON.parse(user));
or
res.send(JSON.stringify(JSON.parse(user)));
and use bodyParser.json() middleware if returning an object.
Likewise in the catch block,
res.status(500).send(‘there was an error’);
and log the error to your console.
——-
Also, fs.readFile takes another param, the encoding. Use ‘utf-8’. It returns a buffer, not a string, if you leave it out.

Adding DELETE operation causes TypeError

I created a Node.js rest api. It follows the general controller, model, schema structure and uses a restify server which I start by running node index.js.
The controller consists of a controllers/baseController.js which contains some operations relevant to all of my controller classes. My controllers/issues.js which extends controllers/baseController.js initially only had a GET, POST and PUT operations. Whilst not complete, these worked fine. They certainly didnt prevent the server fron starting.
I then added the following delete action to my controller:
controller.addAction({
'path': '/issues',
'method': 'DELETE',
'summary': 'Delete all issues from the list',
'responseClass': 'Issues',
'nickname': 'deleteIssues'
}, controller.delete);
It routes to:
delete(req, res, next) {
let collectionContents = this.lib.db.model('Issues');
collectionContents.remove({}, (err, result) => {
if(err) return next(this.RESTError('InternalServerError', err));
this.writeHAL(res, result);
});
}
However, when I try to start my server I get this error:
Debugger listening on ws://127.0.0.1:30333/71b18332-4ac6-49b8-b0ac-86517e9a2190
Debugger attached.
/Users/paulcarron/git/issue-tracker/controllers/baseController.js:19
app[method.toLowerCase()](act['spec']['path'], act['action']);
^
at Issues.setUpActions (/Users/paulcarron/git/issue-tracker/controllers/baseController.js:15:18)
at Object.setupRoutes (/Users/paulcarron/git/issue-tracker/lib/helpers.js:13:12)
at Object.<anonymous> (/Users/paulcarron/git/issue-tracker/index.js:35:13)
at Module._compile (module.js:632:14)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
TypeError: app[method.toLowerCase(...)] is not a function
baseController.js:19
at actions.forEach.act (/Users/paulcarron/git/issue-tracker/controllers/baseController.js:19:32)
at Array.forEach (<anonymous>)
at Issues.setUpActions (/Users/paulcarron/git/issue-tracker/controllers/baseController.js:15:18)
at Object.setupRoutes (/Users/paulcarron/git/issue-tracker/lib/helpers.js:13:12)
at Object.<anonymous> (/Users/paulcarron/git/issue-tracker/index.js:35:13)
at Module._compile (module.js:632:14)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
Waiting for the debugger to disconnect...
baseController.js is here.
It seems to have an issue with 'method': 'DELETE'. However, I can't figure out why. I thought it may be Swagger related as I believe the functions such as addGET, addPOST etc are there and that maybe addDELETE doesn't exist but I checked and it's there. Can anybody explain what might be wrong here?
Additional info.
I think I'm making some progress. The specific point where I'm getting my issue is with method.toLowerCase(). When setting up DELETE, this is essentially DELETE.toLowerCase() but this isn't allowed because delete is a reserved word(I think). Does that seem correct and if so how wo I resolve it?

How to run jQuery in node.js [duplicate]

This question already has answers here:
Can I use jQuery with Node.js?
(21 answers)
Closed 4 years ago.
I have tried npm install jQuery --save and in my node file var $ = require('jquery'); but, then when I run my node file with
$.getJSON('https://en.wikipedia.org/wiki/Washington,_D.C.', function(data) {
//data is the JSON string
});
I get the error
TypeError: $.getJSON is not a function
at Object.<anonymous> (C:\Users\Karim\node 2\tweetPic.js:16:3)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I have also tried importing jquery using
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
});
which just returns
TypeError: require(...).env is not a function
at Object.<anonymous> (C:\Users\Karim\node 2\tweetPic.js:3:18)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I have installed the jsdom package in a similar fashion. Is there something wrong with my jquery code itself? How can I fix this?
Edit: It seems jQuery isn't really what I need here. I'm just going to look into a different way of retrieving json data.
Sorry but i don't know how to install jquery. But you apparently need it to request a website and fetch json. You could use request for that. Hope i helped you.
And you could do like :
request('https://en.wikipedia.org/wiki/Washington,_D.C.', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});

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");

Modules in Node.js

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;

Categories

Resources