Read files from a directory using Promises V2

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
1
down vote

favorite












Follow up to Read files from a directory using Promises



Removed exists() and replaced with stat() so I can check if the file is readable before proceeding.



console.log("Hi");
const fs = require('fs');
const promisify = require('util');

function mystat(file)
return new Promise(function(resolve, reject)
console.log(file);
fs.stat(file, function(err, stat)
if (err)
reject(err);

else
console.log("Returning Obj");
resolve(stat: stat, file: file);

);
);




readdir = promisify(fs.readdir);
readFile = promisify(fs.readFile);
writeFile = promisify(fs.writeFile);

readdir(".")
.then(files => mystat(files[0]))
.then(data => fs.S_IRWXO)) throw "Not Readable"; return readFile(data.file))
.then(content => writeFile('Test', content))
.then(() => console.log("It worked"))
.catch(err => console.log("Error: " + err));


To pass parameters through, eg the file passed through stat to the read function; I needed to define my own function so that I could pass the object on). Is there a better way of doing this?







share|improve this question

























    up vote
    1
    down vote

    favorite












    Follow up to Read files from a directory using Promises



    Removed exists() and replaced with stat() so I can check if the file is readable before proceeding.



    console.log("Hi");
    const fs = require('fs');
    const promisify = require('util');

    function mystat(file)
    return new Promise(function(resolve, reject)
    console.log(file);
    fs.stat(file, function(err, stat)
    if (err)
    reject(err);

    else
    console.log("Returning Obj");
    resolve(stat: stat, file: file);

    );
    );




    readdir = promisify(fs.readdir);
    readFile = promisify(fs.readFile);
    writeFile = promisify(fs.writeFile);

    readdir(".")
    .then(files => mystat(files[0]))
    .then(data => fs.S_IRWXO)) throw "Not Readable"; return readFile(data.file))
    .then(content => writeFile('Test', content))
    .then(() => console.log("It worked"))
    .catch(err => console.log("Error: " + err));


    To pass parameters through, eg the file passed through stat to the read function; I needed to define my own function so that I could pass the object on). Is there a better way of doing this?







    share|improve this question





















      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      Follow up to Read files from a directory using Promises



      Removed exists() and replaced with stat() so I can check if the file is readable before proceeding.



      console.log("Hi");
      const fs = require('fs');
      const promisify = require('util');

      function mystat(file)
      return new Promise(function(resolve, reject)
      console.log(file);
      fs.stat(file, function(err, stat)
      if (err)
      reject(err);

      else
      console.log("Returning Obj");
      resolve(stat: stat, file: file);

      );
      );




      readdir = promisify(fs.readdir);
      readFile = promisify(fs.readFile);
      writeFile = promisify(fs.writeFile);

      readdir(".")
      .then(files => mystat(files[0]))
      .then(data => fs.S_IRWXO)) throw "Not Readable"; return readFile(data.file))
      .then(content => writeFile('Test', content))
      .then(() => console.log("It worked"))
      .catch(err => console.log("Error: " + err));


      To pass parameters through, eg the file passed through stat to the read function; I needed to define my own function so that I could pass the object on). Is there a better way of doing this?







      share|improve this question











      Follow up to Read files from a directory using Promises



      Removed exists() and replaced with stat() so I can check if the file is readable before proceeding.



      console.log("Hi");
      const fs = require('fs');
      const promisify = require('util');

      function mystat(file)
      return new Promise(function(resolve, reject)
      console.log(file);
      fs.stat(file, function(err, stat)
      if (err)
      reject(err);

      else
      console.log("Returning Obj");
      resolve(stat: stat, file: file);

      );
      );




      readdir = promisify(fs.readdir);
      readFile = promisify(fs.readFile);
      writeFile = promisify(fs.writeFile);

      readdir(".")
      .then(files => mystat(files[0]))
      .then(data => fs.S_IRWXO)) throw "Not Readable"; return readFile(data.file))
      .then(content => writeFile('Test', content))
      .then(() => console.log("It worked"))
      .catch(err => console.log("Error: " + err));


      To pass parameters through, eg the file passed through stat to the read function; I needed to define my own function so that I could pass the object on). Is there a better way of doing this?









      share|improve this question










      share|improve this question




      share|improve this question









      asked Mar 23 at 19:15









      Martin York

      70.9k481244




      70.9k481244




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          3
          down vote













          First of all, async code is not a requirement for all Node.js code. It depends on the use case. Async code makes sense if you want to service multiple things concurrently (i.e. HTTP servers, test runners, etc.) but doesn't make sense for single-run script-y things (i.e. cli tool, scaffold generator, etc.).



          The case above falls in the second category, a simple, single-run, non-concurrent, non-intensive operation. This means you can get away with the synchronous versions of the same operations, which will not require promises.



          const readdirSync, statSync, readFileSync, writeFileSync = require('fs');

          readdirSync('.')
          .slice(0, 1)
          .map(file => ( stat: statSync(f), file ))
          // If you know it's not readable, just don't proceed.
          .filter(data => (data.stat.mode | fs.S_IRWXO))
          .map(data => readFileSync(data.file))
          .forEach(content => writeFileSync('test', content))

          // If it made it all the way here, it worked. If something threw up,
          // it should have halted the script somewhere in the middle.
          console.log("It worked")


          Now if you really want async code, Node supports async/await. It's essentially syntactic sugar to promises, where async functions return promises, values returned by async functions become the resolved value, errors throw become rejection values, and await makes code appear to wait for the promise to settle before proceeding. This means you can write the code much closer to the one above.



          The one nice thing about async/await over regular promises is better scoping. You don't have to pass forward stuff from the previous then to the next then.



          const promisify = require('util')
          const fs = require('fs')
          const readdir = promisify(fs.readdir)
          const readFile = promisify(fs.readFile)
          const writeFile = promisify(fs.writeFile)
          const stat = promisify(fs.stat)

          async function op()
          const files = await readdir('.')
          const file = files[0]
          const data = await stat(file)

          if (!(data.stat.mode

          // Needed, since Node will warn you about unhandled rejections.
          // Otherwise, the code above could have been an async iife.
          op().then(() =>
          console.log("It worked")
          , (e) =>
          console.log("Error: " + e)
          )





          share|improve this answer





















          • This is a very simple example (that does something slightly useful). But what I am trying to learn the best way to use async code. Does await block the thread or simply provide a way to make the code look sequential or does it still allow truly async behavior?
            – Martin York
            Mar 23 at 21:50










          • @MartinYork await doesn't block the thread, it just makes it look like it does. It's still the same machinery as promises - it doesn't run the next then unless the previous one settles. A good way to transition from promsies to async/await is to think of it as promises and then, except without the then around your code.
            – Joseph
            Mar 24 at 0:06











          • Thanks that should make life easier.
            – Martin York
            Mar 24 at 0:09










          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          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: "196"
          ;
          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',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190329%2fread-files-from-a-directory-using-promises-v2%23new-answer', 'question_page');

          );

          Post as a guest






























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          3
          down vote













          First of all, async code is not a requirement for all Node.js code. It depends on the use case. Async code makes sense if you want to service multiple things concurrently (i.e. HTTP servers, test runners, etc.) but doesn't make sense for single-run script-y things (i.e. cli tool, scaffold generator, etc.).



          The case above falls in the second category, a simple, single-run, non-concurrent, non-intensive operation. This means you can get away with the synchronous versions of the same operations, which will not require promises.



          const readdirSync, statSync, readFileSync, writeFileSync = require('fs');

          readdirSync('.')
          .slice(0, 1)
          .map(file => ( stat: statSync(f), file ))
          // If you know it's not readable, just don't proceed.
          .filter(data => (data.stat.mode | fs.S_IRWXO))
          .map(data => readFileSync(data.file))
          .forEach(content => writeFileSync('test', content))

          // If it made it all the way here, it worked. If something threw up,
          // it should have halted the script somewhere in the middle.
          console.log("It worked")


          Now if you really want async code, Node supports async/await. It's essentially syntactic sugar to promises, where async functions return promises, values returned by async functions become the resolved value, errors throw become rejection values, and await makes code appear to wait for the promise to settle before proceeding. This means you can write the code much closer to the one above.



          The one nice thing about async/await over regular promises is better scoping. You don't have to pass forward stuff from the previous then to the next then.



          const promisify = require('util')
          const fs = require('fs')
          const readdir = promisify(fs.readdir)
          const readFile = promisify(fs.readFile)
          const writeFile = promisify(fs.writeFile)
          const stat = promisify(fs.stat)

          async function op()
          const files = await readdir('.')
          const file = files[0]
          const data = await stat(file)

          if (!(data.stat.mode

          // Needed, since Node will warn you about unhandled rejections.
          // Otherwise, the code above could have been an async iife.
          op().then(() =>
          console.log("It worked")
          , (e) =>
          console.log("Error: " + e)
          )





          share|improve this answer





















          • This is a very simple example (that does something slightly useful). But what I am trying to learn the best way to use async code. Does await block the thread or simply provide a way to make the code look sequential or does it still allow truly async behavior?
            – Martin York
            Mar 23 at 21:50










          • @MartinYork await doesn't block the thread, it just makes it look like it does. It's still the same machinery as promises - it doesn't run the next then unless the previous one settles. A good way to transition from promsies to async/await is to think of it as promises and then, except without the then around your code.
            – Joseph
            Mar 24 at 0:06











          • Thanks that should make life easier.
            – Martin York
            Mar 24 at 0:09














          up vote
          3
          down vote













          First of all, async code is not a requirement for all Node.js code. It depends on the use case. Async code makes sense if you want to service multiple things concurrently (i.e. HTTP servers, test runners, etc.) but doesn't make sense for single-run script-y things (i.e. cli tool, scaffold generator, etc.).



          The case above falls in the second category, a simple, single-run, non-concurrent, non-intensive operation. This means you can get away with the synchronous versions of the same operations, which will not require promises.



          const readdirSync, statSync, readFileSync, writeFileSync = require('fs');

          readdirSync('.')
          .slice(0, 1)
          .map(file => ( stat: statSync(f), file ))
          // If you know it's not readable, just don't proceed.
          .filter(data => (data.stat.mode | fs.S_IRWXO))
          .map(data => readFileSync(data.file))
          .forEach(content => writeFileSync('test', content))

          // If it made it all the way here, it worked. If something threw up,
          // it should have halted the script somewhere in the middle.
          console.log("It worked")


          Now if you really want async code, Node supports async/await. It's essentially syntactic sugar to promises, where async functions return promises, values returned by async functions become the resolved value, errors throw become rejection values, and await makes code appear to wait for the promise to settle before proceeding. This means you can write the code much closer to the one above.



          The one nice thing about async/await over regular promises is better scoping. You don't have to pass forward stuff from the previous then to the next then.



          const promisify = require('util')
          const fs = require('fs')
          const readdir = promisify(fs.readdir)
          const readFile = promisify(fs.readFile)
          const writeFile = promisify(fs.writeFile)
          const stat = promisify(fs.stat)

          async function op()
          const files = await readdir('.')
          const file = files[0]
          const data = await stat(file)

          if (!(data.stat.mode

          // Needed, since Node will warn you about unhandled rejections.
          // Otherwise, the code above could have been an async iife.
          op().then(() =>
          console.log("It worked")
          , (e) =>
          console.log("Error: " + e)
          )





          share|improve this answer





















          • This is a very simple example (that does something slightly useful). But what I am trying to learn the best way to use async code. Does await block the thread or simply provide a way to make the code look sequential or does it still allow truly async behavior?
            – Martin York
            Mar 23 at 21:50










          • @MartinYork await doesn't block the thread, it just makes it look like it does. It's still the same machinery as promises - it doesn't run the next then unless the previous one settles. A good way to transition from promsies to async/await is to think of it as promises and then, except without the then around your code.
            – Joseph
            Mar 24 at 0:06











          • Thanks that should make life easier.
            – Martin York
            Mar 24 at 0:09












          up vote
          3
          down vote










          up vote
          3
          down vote









          First of all, async code is not a requirement for all Node.js code. It depends on the use case. Async code makes sense if you want to service multiple things concurrently (i.e. HTTP servers, test runners, etc.) but doesn't make sense for single-run script-y things (i.e. cli tool, scaffold generator, etc.).



          The case above falls in the second category, a simple, single-run, non-concurrent, non-intensive operation. This means you can get away with the synchronous versions of the same operations, which will not require promises.



          const readdirSync, statSync, readFileSync, writeFileSync = require('fs');

          readdirSync('.')
          .slice(0, 1)
          .map(file => ( stat: statSync(f), file ))
          // If you know it's not readable, just don't proceed.
          .filter(data => (data.stat.mode | fs.S_IRWXO))
          .map(data => readFileSync(data.file))
          .forEach(content => writeFileSync('test', content))

          // If it made it all the way here, it worked. If something threw up,
          // it should have halted the script somewhere in the middle.
          console.log("It worked")


          Now if you really want async code, Node supports async/await. It's essentially syntactic sugar to promises, where async functions return promises, values returned by async functions become the resolved value, errors throw become rejection values, and await makes code appear to wait for the promise to settle before proceeding. This means you can write the code much closer to the one above.



          The one nice thing about async/await over regular promises is better scoping. You don't have to pass forward stuff from the previous then to the next then.



          const promisify = require('util')
          const fs = require('fs')
          const readdir = promisify(fs.readdir)
          const readFile = promisify(fs.readFile)
          const writeFile = promisify(fs.writeFile)
          const stat = promisify(fs.stat)

          async function op()
          const files = await readdir('.')
          const file = files[0]
          const data = await stat(file)

          if (!(data.stat.mode

          // Needed, since Node will warn you about unhandled rejections.
          // Otherwise, the code above could have been an async iife.
          op().then(() =>
          console.log("It worked")
          , (e) =>
          console.log("Error: " + e)
          )





          share|improve this answer













          First of all, async code is not a requirement for all Node.js code. It depends on the use case. Async code makes sense if you want to service multiple things concurrently (i.e. HTTP servers, test runners, etc.) but doesn't make sense for single-run script-y things (i.e. cli tool, scaffold generator, etc.).



          The case above falls in the second category, a simple, single-run, non-concurrent, non-intensive operation. This means you can get away with the synchronous versions of the same operations, which will not require promises.



          const readdirSync, statSync, readFileSync, writeFileSync = require('fs');

          readdirSync('.')
          .slice(0, 1)
          .map(file => ( stat: statSync(f), file ))
          // If you know it's not readable, just don't proceed.
          .filter(data => (data.stat.mode | fs.S_IRWXO))
          .map(data => readFileSync(data.file))
          .forEach(content => writeFileSync('test', content))

          // If it made it all the way here, it worked. If something threw up,
          // it should have halted the script somewhere in the middle.
          console.log("It worked")


          Now if you really want async code, Node supports async/await. It's essentially syntactic sugar to promises, where async functions return promises, values returned by async functions become the resolved value, errors throw become rejection values, and await makes code appear to wait for the promise to settle before proceeding. This means you can write the code much closer to the one above.



          The one nice thing about async/await over regular promises is better scoping. You don't have to pass forward stuff from the previous then to the next then.



          const promisify = require('util')
          const fs = require('fs')
          const readdir = promisify(fs.readdir)
          const readFile = promisify(fs.readFile)
          const writeFile = promisify(fs.writeFile)
          const stat = promisify(fs.stat)

          async function op()
          const files = await readdir('.')
          const file = files[0]
          const data = await stat(file)

          if (!(data.stat.mode

          // Needed, since Node will warn you about unhandled rejections.
          // Otherwise, the code above could have been an async iife.
          op().then(() =>
          console.log("It worked")
          , (e) =>
          console.log("Error: " + e)
          )






          share|improve this answer













          share|improve this answer



          share|improve this answer











          answered Mar 23 at 21:09









          Joseph

          22.1k21833




          22.1k21833











          • This is a very simple example (that does something slightly useful). But what I am trying to learn the best way to use async code. Does await block the thread or simply provide a way to make the code look sequential or does it still allow truly async behavior?
            – Martin York
            Mar 23 at 21:50










          • @MartinYork await doesn't block the thread, it just makes it look like it does. It's still the same machinery as promises - it doesn't run the next then unless the previous one settles. A good way to transition from promsies to async/await is to think of it as promises and then, except without the then around your code.
            – Joseph
            Mar 24 at 0:06











          • Thanks that should make life easier.
            – Martin York
            Mar 24 at 0:09
















          • This is a very simple example (that does something slightly useful). But what I am trying to learn the best way to use async code. Does await block the thread or simply provide a way to make the code look sequential or does it still allow truly async behavior?
            – Martin York
            Mar 23 at 21:50










          • @MartinYork await doesn't block the thread, it just makes it look like it does. It's still the same machinery as promises - it doesn't run the next then unless the previous one settles. A good way to transition from promsies to async/await is to think of it as promises and then, except without the then around your code.
            – Joseph
            Mar 24 at 0:06











          • Thanks that should make life easier.
            – Martin York
            Mar 24 at 0:09















          This is a very simple example (that does something slightly useful). But what I am trying to learn the best way to use async code. Does await block the thread or simply provide a way to make the code look sequential or does it still allow truly async behavior?
          – Martin York
          Mar 23 at 21:50




          This is a very simple example (that does something slightly useful). But what I am trying to learn the best way to use async code. Does await block the thread or simply provide a way to make the code look sequential or does it still allow truly async behavior?
          – Martin York
          Mar 23 at 21:50












          @MartinYork await doesn't block the thread, it just makes it look like it does. It's still the same machinery as promises - it doesn't run the next then unless the previous one settles. A good way to transition from promsies to async/await is to think of it as promises and then, except without the then around your code.
          – Joseph
          Mar 24 at 0:06





          @MartinYork await doesn't block the thread, it just makes it look like it does. It's still the same machinery as promises - it doesn't run the next then unless the previous one settles. A good way to transition from promsies to async/await is to think of it as promises and then, except without the then around your code.
          – Joseph
          Mar 24 at 0:06













          Thanks that should make life easier.
          – Martin York
          Mar 24 at 0:09




          Thanks that should make life easier.
          – Martin York
          Mar 24 at 0:09












           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190329%2fread-files-from-a-directory-using-promises-v2%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Greedy Best First Search implementation in Rust

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          C++11 CLH Lock Implementation