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.
Related
I have a problem in creating the main file for my discord bot. currently, i encountered a problem in trying to get my bot to work but sadly, this error message has been outputted from the console.
PS C:\Users\Kelvin Wang\Documents\Projects\DiscordBot> node index.js
node:internal/modules/cjs/loader:1170
throw err;
^
SyntaxError: C:\Users\Kelvin Wang\Documents\Projects\DiscordBot\config.json: Unexpected end of JSON input
at parse (<anonymous>)
at Object.Module._extensions..json (node:internal/modules/cjs/loader:1167:22)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:\Users\Kelvin Wang\Documents\Projects\DiscordBot\index.js:4:19)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
My code in index.js is this:
//initial discord initialization of client and library
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const dotenv = require('dotenv');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ferraribot is online!');
});
// Login to Discord with your client's token
client.login(token);
While my config.json looks like this:
{
"token": "token"
}
Any help would be much appreciated! This is my first time using stack overflow so I'm sorry for any wrong formatting that I've done. Thanks in advance!
Your code looks just fine.
The error said, your code has some problems reading the JSON config. (is it in the same directory?)
First try your code using your token in the index.js. client.login(*****) // just don't upload e.g. github ;)
Second, I believe better practice using .env for sensitive information. https://www.npmjs.com/package/dotenv
When I would enter
"node index.js"
Into Command Prompt & the folder with all of the Discord bot information, it'd give me this error:
const client = Discord.Client();
^^^^^
SyntaxError: Unexpected token const
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Anyway to fix?
Edit:
config.json
{
"BOT_TOKEN": "bot's token"
}
index.js
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.login('bot's token');
From what i can see, you have probably put one of these somewhere in the code: (maybe by accident in another .js file?)
const client = Discord.client();
SyntaxError: Unexpected token const, usually means the app waited for some kind of const, but did not receive it.
Also, try to move the 'Token' constant in your index.js file.
It's suggesting somewhere in your code you have const client = Discord.Client();. Once found just remove it.
Advice
I'd suggest you refer to your config.json .
The following:
const settings = require('./config.json')
Then extract bot token by making a variable:
const token = settings.BOT_TOKEN;
Result:
client.login(token);
Optimises your code ;)
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);
}
});
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();
});
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