0
votes

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?

2
Never ever use eval to parse JSON! In node.js, JSON.parse is always available.Bergi
What is Promise.promisify? Did you mean util.promisify?Bergi
I don't get any error using the code you posted.Bergi
Yup.. I meant util.promisify(), however I guess that's not causing this issue. @Bergi Was there any code change done apart from the util.promisify? I'm still getting the same errortechnoJ
Looks like node v6.11.3 does not support async/await syntax. Update it.Bergi

2 Answers

3
votes
0
votes

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.