Node.js async await in express












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?










share|improve this question


















  • 3




    Never ever use eval to parse JSON! In node.js, JSON.parse is always available.
    – Bergi
    Nov 20 at 9:00










  • What is Promise.promisify? Did you mean util.promisify?
    – Bergi
    Nov 20 at 9:01










  • I don't get any error using the code you posted.
    – Bergi
    Nov 20 at 9: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 at 9:04








  • 1




    Looks like node v6.11.3 does not support async/await syntax. Update it.
    – Bergi
    Nov 20 at 9:14
















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?










share|improve this question


















  • 3




    Never ever use eval to parse JSON! In node.js, JSON.parse is always available.
    – Bergi
    Nov 20 at 9:00










  • What is Promise.promisify? Did you mean util.promisify?
    – Bergi
    Nov 20 at 9:01










  • I don't get any error using the code you posted.
    – Bergi
    Nov 20 at 9: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 at 9:04








  • 1




    Looks like node v6.11.3 does not support async/await syntax. Update it.
    – Bergi
    Nov 20 at 9:14














0












0








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?










share|improve this question













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?







javascript node.js express async-await






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 8:46









technoJ

1416




1416








  • 3




    Never ever use eval to parse JSON! In node.js, JSON.parse is always available.
    – Bergi
    Nov 20 at 9:00










  • What is Promise.promisify? Did you mean util.promisify?
    – Bergi
    Nov 20 at 9:01










  • I don't get any error using the code you posted.
    – Bergi
    Nov 20 at 9: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 at 9:04








  • 1




    Looks like node v6.11.3 does not support async/await syntax. Update it.
    – Bergi
    Nov 20 at 9:14














  • 3




    Never ever use eval to parse JSON! In node.js, JSON.parse is always available.
    – Bergi
    Nov 20 at 9:00










  • What is Promise.promisify? Did you mean util.promisify?
    – Bergi
    Nov 20 at 9:01










  • I don't get any error using the code you posted.
    – Bergi
    Nov 20 at 9: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 at 9:04








  • 1




    Looks like node v6.11.3 does not support async/await syntax. Update it.
    – Bergi
    Nov 20 at 9:14








3




3




Never ever use eval to parse JSON! In node.js, JSON.parse is always available.
– Bergi
Nov 20 at 9:00




Never ever use eval to parse JSON! In node.js, JSON.parse is always available.
– Bergi
Nov 20 at 9:00












What is Promise.promisify? Did you mean util.promisify?
– Bergi
Nov 20 at 9:01




What is Promise.promisify? Did you mean util.promisify?
– Bergi
Nov 20 at 9:01












I don't get any error using the code you posted.
– Bergi
Nov 20 at 9:03




I don't get any error using the code you posted.
– Bergi
Nov 20 at 9: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 at 9:04






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 at 9:04






1




1




Looks like node v6.11.3 does not support async/await syntax. Update it.
– Bergi
Nov 20 at 9:14




Looks like node v6.11.3 does not support async/await syntax. Update it.
– Bergi
Nov 20 at 9:14












2 Answers
2






active

oldest

votes


















2














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






share|improve this answer























  • should be version 8. Nodejs 7.5 supports async await only with the harmony flag
    – sheplu
    Nov 20 at 9:12












  • Indeed, updated the original answer
    – Johannes Obermair
    Nov 20 at 9:52










  • Thanks.. It did work after ugrading the node version to v10.13.0
    – technoJ
    Nov 20 at 9:58



















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.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389202%2fnode-js-async-await-in-express%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














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






    share|improve this answer























    • should be version 8. Nodejs 7.5 supports async await only with the harmony flag
      – sheplu
      Nov 20 at 9:12












    • Indeed, updated the original answer
      – Johannes Obermair
      Nov 20 at 9:52










    • Thanks.. It did work after ugrading the node version to v10.13.0
      – technoJ
      Nov 20 at 9:58
















    2














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






    share|improve this answer























    • should be version 8. Nodejs 7.5 supports async await only with the harmony flag
      – sheplu
      Nov 20 at 9:12












    • Indeed, updated the original answer
      – Johannes Obermair
      Nov 20 at 9:52










    • Thanks.. It did work after ugrading the node version to v10.13.0
      – technoJ
      Nov 20 at 9:58














    2












    2








    2






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






    share|improve this answer














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







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 20 at 9:19

























    answered Nov 20 at 9:10









    Johannes Obermair

    214




    214












    • should be version 8. Nodejs 7.5 supports async await only with the harmony flag
      – sheplu
      Nov 20 at 9:12












    • Indeed, updated the original answer
      – Johannes Obermair
      Nov 20 at 9:52










    • Thanks.. It did work after ugrading the node version to v10.13.0
      – technoJ
      Nov 20 at 9:58


















    • should be version 8. Nodejs 7.5 supports async await only with the harmony flag
      – sheplu
      Nov 20 at 9:12












    • Indeed, updated the original answer
      – Johannes Obermair
      Nov 20 at 9:52










    • Thanks.. It did work after ugrading the node version to v10.13.0
      – technoJ
      Nov 20 at 9:58
















    should be version 8. Nodejs 7.5 supports async await only with the harmony flag
    – sheplu
    Nov 20 at 9:12






    should be version 8. Nodejs 7.5 supports async await only with the harmony flag
    – sheplu
    Nov 20 at 9:12














    Indeed, updated the original answer
    – Johannes Obermair
    Nov 20 at 9:52




    Indeed, updated the original answer
    – Johannes Obermair
    Nov 20 at 9:52












    Thanks.. It did work after ugrading the node version to v10.13.0
    – technoJ
    Nov 20 at 9:58




    Thanks.. It did work after ugrading the node version to v10.13.0
    – technoJ
    Nov 20 at 9:58













    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.






    share|improve this answer




























      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.






      share|improve this answer


























        0












        0








        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.






        share|improve this answer














        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 20 at 9:12

























        answered Nov 20 at 9:07









        Steven Spungin

        6,58332230




        6,58332230






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389202%2fnode-js-async-await-in-express%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Costa Masnaga