repl node js problem SyntaxError: Unexpected identifier - javascript

I am trying to learn node js.
so I used the below example and implemented in repl.
https://medium.freecodecamp.org/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2
but I am not able to run the app.
when I run the app I am getting the below error.
can you tell me how to fix it.
providing my code base below.
is there any online editor where I can run node js and see
https://repl.it/#doadhdoadh/IdleAccurateSource
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
require('./app/routes')(app, {});
app.listen(port, () => {
console.log('We are live on ' + port);
});
node v9.7.1 linux/amd64
npm dev
evalmachine.<anonymous>:1
npm dev
^^^
SyntaxError: Unexpected identifier
at new Script (vm.js:51:7)
at createScript (vm.js:136:10)
at Object.runInContext (vm.js:181:10)
at evaluate (/run_dir/repl.js:133:14)
at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
at ReadStream.emit (events.js:180:13)
at addChunk (_stream_readable.js:274:12)
at readableAddChunk (_stream_readable.js:261:11)
at ReadStream.Readable.push (_stream_readable.js:218:10)
at fs.read (fs.js:2124:12)

I went through the original server.js file and found that you were missing a semicolon on line 12 i.e db = database.db("api");
Update
I just realised that the repl NodeJs demo gets triggered using index.js file. I just exported a function in server.js and imported it in index.js to trigger the server creation process.
Check the updated poc
Hope it works!

Related

Nodemon: app crashed waiting for file changes before starting... on Windows

I implemented express code with the mongoose database but I have faced "nodemon crushed" error for that I followed the below techniques but still, now I have faced this error.
Node version: v16.14.2
NPM version: 8.5.0
I have followed some steps to solve this issue and that is given below,
Open Windows Task Manager is given in the attached file
End Task (Node.js JavaScript Runtime)
But the problem is not solved!
Here is the code of server.js
const express = require('express')
const mongoose = require('mongoose')
const app = express()
mongoose.connect('mongodb://localhost:27017/my-students');
const studentRoute = require('./api/routes/studentsRoute');
//========> Routing Starting
app.use('/api/students', studentRoute);
//========> Routing End
//========> MongoDB Database connection and Check
const db = mongoose.connection;
db.on('error', (err) =>{
console.log(err);
})
db.once('open', ()=>{
console.log("Database connection Established!")
})
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>{
console.log(`Server running on PORT #${PORT}`)
})
Windows Task Manager where I end the task by clicking "End Task" of "Node.js JavaScript Runtime" but it was not solved the issue and the Task Manager file attached below,
Error screenshot is given below the attached file,
The problem is arising from this line
const studentRoute = require('./api/routes/studentsRoute');
check if you have this included in that file
module.exports = router
Reference: TypeError: Router.use() requires middleware function but got a Object

node server not running : exiting without any output

I've been messing around with codesphere lately and have a weird issue, at least to me:
my server.js:
const express =require('express');
const app = express();
const port = 8000;
app.get('/', (req,res) => {
res.send('Hi there')
});
app.listen(port, () => {
console.log("Running")
});
Upon npm start :
user#codesphere:app [master] $ npm start
personal_website#1.0.0 start /home/user/app
node server.js
then the output exits the server and returns to CLI
Output for running node server.js:
Another edit:
upper part, my package.json in their ide, lower part: package.json open in terminal (nano)
Now I actually think, it is save to assume they have trouble!

Does log4js require any extra code to work on an Apache server?

I'm trying to add Log4js-Node to a Node.js server running on Apache. Here's my code:
const path = require("path");
const express = require("express");
const log4js = require('log4js');
const app = express();
const logger = log4js.getLogger();
logger.level = "debug";
const port = 443;
log4js.configure({
appenders: { everything: { type: 'file', filename: 'logs.log', flags: 'w' } },
categories: { default: { appenders: ['everything'], level: 'ALL' } }
});
const server = app.listen(port, () => {
logger.debug("listening to requests on port " + port);
});
app.get("/log", (req, res) => {
res.sendFile(path.join(__dirname + "/logs.log"));
});
When I run the script on Node.js on my computer and navigate to localhost:443/log I see what I expect, which is this:
[2020-03-17T22:50:43.145] [DEBUG] default - listening to requests on port 443
But when I run the code on a remote server it crashes and I get this in the error page (with part of the path replaced by me with "[removed]"):
App 25925 output: at Server. ([removed]/index.js:27:9)
App 25925 output: at Logger. [as debug] ([removed]/12/lib/node_modules/log4js/lib/logger.js:124:10)
App 25925 output: at Logger.log ([removed]/12/lib/node_modules/log4js/lib/logger.js:73:12)
App 25925 output: at Logger._log ([removed]/12/lib/node_modules/log4js/lib/logger.js:90:16)
App 25925 output: at Object.send ([removed]/12/lib/node_modules/log4js/lib/clustering.js:97:15)
App 25925 output: [removed]/12/lib/node_modules/log4js/lib/clustering.js:97
App 25925 output: at Object. ([removed]/12/lib/node_modules/log4js/lib/clustering.js:8:13)
I'm using A2 Hosting which uses Apache 2.4.41. I opted for Node.js 12.9.0, and Log4js 6.1.2. The package.json should be the same on both my computer and the server, and I've run npm install on both.
Is this just an issue with Log4js and the server, or have I missed something somewhere?
This was actually a relatively simple fix. The path referenced by the last error in the stack trace is a Log4js module that implements clustering support through Node's "cluster" module. The line "8" referenced is cluster = require("cluster"). It's wrapped in a try/catch block like this:
try {
cluster = require("cluster"); //eslint-disable-line
} catch (e) {
debug("cluster module not present");
disabled = true;
}
The installation of Node.js on my computer came with the "cluster" module, however as far as I can tell, the server I'm using doesn't support it. Also, the version of Node I'm using on my computer is newer than what I'm using on the server (so I've now installed 12.9 on my machine). I believe the older version of Node doesn't bother trying to catch the exception and tries to load the cluster module, fails, and then throws the error.
So the simple fix was to comment out most of the "try/catch" block, leaving just the contents of "catch" like this:
// try {
// cluster = require("cluster"); //eslint-disable-line
// } catch (e) {
debug("cluster module not present");
disabled = true;
// }
If someone has a better fix, I'm open to suggestions.
The same response of #skittleswrapper,thx, it work for me.
I use Node.js 14.18.1 with log4js 6.3.0.
But i wondering what'is the necessary of this module 'cluster' and if we can
add it to our app in other way.

TypeError: PUBNUB.init is not a function

I am using Node.js and I'm trying to get PubNub integrated to get my chatroom up and running. I have been following numerous tutorials and they all seem to have PubNub executing from their client-side. However, to ensure the security of my publish-key and subscribe-key I want to have PubNub execute from my server-side (Nodejs). However the problem is occurs exactly when I try to do just that. Here is my server:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var request = require('request');
var pubnub = require('pubnub');
pubnub = pubnub.init({
subscribe_key: 'sub-c-demo',
publish_key: 'pub-c-demo',
ssl: true
});
//Defining routes
var routes = require('./routes/index');
//Init express
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
//View Engine
app.set('view engine', 'ejs');
//Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
//Get route
app.use('/', routes);
//Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('3000 is the magic port!!');
});
Why do I get a TypeError: pubnub.init is not a function when I try to initialize pubnub?
$ node server
/Users/macbookpro/Desktop/project007/server.js:8
var pubnub = pubnub.init({
^
TypeError: pubnub.init is not a function
at Object.<anonymous> (/Users/macbookpro/Desktop/project007/server.js:8:21)
at Module._compile (module.js:573:32)
at Object.Module._extensions..js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
at Function.Module._load (module.js:441:3)
at Module.runMain (module.js:607:10)
at run (bootstrap_node.js:382:7)
at startup (bootstrap_node.js:137:9)
at bootstrap_node.js:497:3
I followed what seemed to be all the necessary steps:
npm i pubnub --save
var pubnub = require('pubnub');
https://cdn.pubnub.com/sdk/javascript/pubnub.4.4.2.min.js
(Included the latest sdk in my header)
But there seems to be an error somewhere which has lead to me to be confused about the error as well as a few other things.
1). I have been piecing things together from all three but which of these tutorials should i really be following?
https://vimeo.com/35557579
https://www.pubnub.com/docs/nodejs/pubnub-javascript-sdk-v4
https://www.pubnub.com/docs/javascript/pubnub-javascript-sdk-v4
2). Does my publish-key and subscribe-key need be secured or can I simply run PubNub from my client-side like shown in most tutorials?
3). Forget about the server-side and client, should I be executing PubNub as a javascript file and linking the script? <script src="js/pubnubchatroom.js"></script>
I am new to this stuff and im just trying to wrap my head around it all. Thanks in advance!
PubNub V4 SDK NodeJS new Init
There is a new way to initialize your PubNub SDK. See the following example. v4 SDKs are not drop-in compatible. You can mix v4 and v3 SDKs between environments successfully.
const PubNub = require('pubnub');
const pubnub = new PubNub({
publishKey : 'demo',
subscribeKey : 'demo'
})
Follow https://www.pubnub.com/docs/nodejs/pubnub-javascript-sdk-v4
pub/sub keys can be exposed. never expose your secret key.
PubNub is compatible with any strategy in this regard.

Express has no method configure error

I'm trying to get started with the MEAN stack. And I'm following this tutorial: link
I have made it until the Test Our Server section. Here
// modules =================================================
var express = require('express');
var app = express();
var mongoose= require('mongoose');
// configuration ===========================================
// config files
var db = require('./config/db');
var port = process.env.PORT || 8080; // set our port
mongoose.connect(db.url); // connect to our mongoDB database (uncomment after you enter in your own credentials in config/db.js)
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // have the ability to pull information from html in POST
app.use(express.methodOverride()); // have the ability to simulate DELETE and PUT
});
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:8080
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
When I run
nodemon server.js
I get this error
app.configure(function() {
^
TypeError: Object function (req, res, next) {
app.handle(req, res, next);
} has no method 'configure'
at Object.<anonymous> (C:\Users\Yuksel\Desktop\node\test\server.js:14:5)
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
5 Mar 17:27:20 - [nodemon] app crashed - waiting for file changes before startin
g...
It simply says app has no method configure(I guess). But when I delete the configure part and run it again, it works.(This mean app has .listen method, so it is an express object.)
I have tried with both node and nodemon. And I couldn't figure it out. Thank you for your time.
Tom in his blog post new-features-node-express-4 provides examples of how to convert from using app.configure in express version 3.x to removing it in express version 4.0.
For convenience I added the code example below.
Version 3.x
// all environments
app.configure(function(){
app.set('title', 'Application Title');
})
// development only
app.configure('development', function(){
app.set('mongodb_uri', 'mongo://localhost/dev');
})
// production only
app.configure('production', function(){
app.set('mongodb_uri', 'mongo://localhost/prod');
})
Version 4.0
// all environments
app.set('title', 'Application Title');
// development only
if ('development' == app.get('env')) {
app.set('mongodb_uri', 'mongo://localhost/dev');
}
// production only
if ('production' == app.get('env')) {
app.set('mongodb_uri', 'mongo://localhost/prod');
}
The configure method has been removed from express as of version 4.0.0 (including 4.0.0-rc2). See the changelog at https://github.com/strongloop/express/blob/master/History.md#400--2014-04-09

Categories

Resources