2

I have multiple files that contains data with time stamps, so I want to read these files in order (and line by line), but I found most of the Node packages use asynchronous method to read files, how can I read each line in order and store all the data in to one string before sending it?

I want to do something like:

    function callbackReadFilesAndSend(res, req){
      var data = ""
      for(int i=0; i<numOfFiles;i++){
     //read lines from files
          data+=...//data from Files[i]
     }
   res.send(data)

}

But I think synchronous methods are bad to use in practice.

Thank you.

4
  • Synchronous is only bad if you mix them with asynchronous operation: blog.izs.me/post/59142742143/designing-apis-for-asynchrony Commented Jun 12, 2017 at 3:27
  • In this case, if the file data that I'm sending is not too big, can I use readFileSync in a for loop before send it from the server? Commented Jun 12, 2017 at 3:29
  • Yes you can do that. Although you probably don't want to use data+= to combine all the files together Commented Jun 12, 2017 at 3:31
  • Thank you I'll try tomorrow Commented Jun 12, 2017 at 3:31

2 Answers 2

1

When you want to execute set of known tasks in sequence in node.js you can use something like async.series(tasks[, callback]).

Run the functions in the tasks collection in series, each one running once the previous function has completed.

In other to use async module you must do:

npm install async

and require it in your code:

const async = require('async');

And for this specific purpose (reading the file content), you can use node.js fs synchronous functions like fs.readFileSync(path[, options]).

Sign up to request clarification or add additional context in comments.

Comments

0

fs.readFileSync is a sync method for reading files. https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.