0

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?

technoJ
  • 175
  • 1
  • 1
  • 16
  • 4
    [**Never ever** use `eval` to parse JSON!](https://stackoverflow.com/q/4270597/1048572) In node.js, `JSON.parse` is always available. – Bergi Nov 20 '18 at 09:00
  • What is `Promise.promisify`? Did you mean `util.promisify`? – Bergi Nov 20 '18 at 09:01
  • I don't get any error using the code you posted. – Bergi Nov 20 '18 at 09:03
  • 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 error – technoJ Nov 20 '18 at 09:04
  • 1
    Looks like node v6.11.3 does not support `async`/`await` syntax. Update it. – Bergi Nov 20 '18 at 09:14
  • asyn-await feature available from node version 8+ only. If you cannot change the version, try using generator functions with Co. – Shishir Sonekar Nov 20 '18 at 09:58

2 Answers2

3

Async/await is only available in Node versions 8 an up. Try using a newer Node version if possible.

0

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.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78