Unexpected token: io.listen(server) - javascript

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

Related

Update JSON file write not working in NodeJS

I'm trying to read existing JSON file and update the existing value and saving it back. I'm getting below error message:
node:internal/modules/cjs/loader:944
throw err;
^
Error: Cannot find module 'src/myApp/test.json'
Require stack:
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:941:15)
at Function.Module._load (node:internal/modules/cjs/loader:774:27)
at Module.require (node:internal/modules/cjs/loader:1013:19)
at require (node:internal/modules/cjs/helpers:93:18)
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
at Module.load (node:internal/modules/cjs/loader:989:32)
at Function.Module._load (node:internal/modules/cjs/loader:829:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) {
code: 'MODULE_NOT_FOUND',
}
Please find the code below -
Much appreciated if someone can help me to fix this issue.
test.json
{
"key": ""
}
updateJSON.js
const fs = require('fs');
const fileName = 'src/myApp/test.json';
const file = require(fileName);
file.key = "new value";
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
if (err) return console.log(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
});
The error message Error: Cannot find module 'src/myApp/test.json' indicates that the Node.js cannot resolve the src/myApp/test.json file correctly.
By default, the name(src/myApp/test.json here) not starting with ./ will be recognized as a module of Node.js and will be resolved from native modules and node_modules, which leads to the error.
Using a relative path like ../src/myApp/test.json should fix it.
Ref: https://nodejs.org/api/modules.html#modules_require_id

html-pdf: Failed to load PhantomJS module. Error: Cannot find module 'phantomjs-prebuilt'

I am using html-pdf NPM module to convert my html (bill.html) code to pdf file (bill.pdf), I have simple html with heading tag and exporting that html by fs module below
import { create } from 'html-pdf';
import fs from 'fs';
import path from 'path';
var html = fs.readFileSync(path.resolve(__dirname, "./bill.html"), 'utf8');
var options = { format: 'Letter' };
create(html, options).toFile('./bill.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res);
});
And I am getting this error of 'phantomjs-prebuilt'
html-pdf: Failed to load PhantomJS module. Error: Cannot find module 'phantomjs-prebuilt'
Require stack:
- /home/hardy/Documents/personal/api/node_modules/html-pdf/lib/pdf.js
- /home/hardy/Documents/personal/api/node_modules/html-pdf/lib/index.js
- /home/hardy/Documents/personal/api/src/app.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/hardy/Documents/personal/api/node_modules/html-pdf/lib/pdf.js:7:19)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Object.require.extensions.<computed> [as .js] (/home/hardy/Documents/personal/api/node_modules/babel-register/lib/node.js:152:7)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/home/hardy/Documents/personal/api/node_modules/html-pdf/lib/pdf.js',
'/home/hardy/Documents/personal/api/node_modules/html-pdf/lib/index.js',
'/home/hardy/Documents/personal/api/src/app.js'
]
}
Debugger listening on ws://127.0.0.1:5858/508c0ea9-c495-4254-9b05-cd2fd3cd8ae3
For help, see: https://nodejs.org/en/docs/inspector
assert.js:374
throw err;
^
AssertionError [ERR_ASSERTION] [ERR_ASSERTION]: html-pdf: Failed to load PhantomJS module. You have to set the path to the PhantomJS binary using 'options.phantomPath'
at new PDF (/home/hardy/Documents/personal/api/node_modules/html-pdf/lib/pdf.js:38:3)
at createPdf (/home/hardy/Documents/personal/api/node_modules/html-pdf/lib/index.js:10:14)
at Object.<anonymous> (/home/hardy/Documents/personal/api/src/app.js:8:1)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at loader (/home/hardy/Documents/personal/api/node_modules/babel-register/lib/node.js:144:5)
at Object.require.extensions.<computed> [as .js] (/home/hardy/Documents/personal/api/node_modules/babel-register/lib/node.js:154:7)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at Object.<anonymous> (/home/hardy/Documents/personal/api/node_modules/babel-cli/lib/_babel-node.js:154:22) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: undefined,
expected: true,
operator: '=='
}
Waiting for the debugger to disconnect...
As phantomjs-rebuilt is a deprecated
You can still install it forcefully and resolve the error.
Command - npm i phantomjs-prebuilt --force

Error: Cannot find module 'config' at Function.Module._resolveFilename

Hii I have simple node server, with the following structure
myapp
-config
-default-json
-index.js
-package-lock.json
-package.json
Here is my part of my index.js
'use strict';
const
config = require('config'),
express = require('express'),
request = require('request'),
body_parser = require('body-parser'),
app = express().use(body_parser.json()); // creates express http server
// Sets server port and logs message on success
app.listen(process.env.PORT || 1337, () => console.log('webhook is listening'));
when I run node index.js I get the following error
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module 'config'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (C:\xampp\htdocs\chat\index.js:13:14)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
what is wrong with my code?
I found solution by by installing config from npm
https://www.npmjs.com/package/config
follow the instruction above and it should work , it might help some one in future
You have to explicitly add the config module in your package.json:
"dependencies": {
"config": "version number"
}
https://www.npmjs.com/package/config
It means there is no config.js in your current location. Put the exact location of the config.js file..
Try,
config = require('./config/config'),

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

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