In my application, I am trying to read a file and then write the contents of the file to another file.
I have used bluebird promises to do this. I need help to confirm that my understanding on using promises is right in my implementation.
The questions that I have is,
In my example, I am first reading the file, then once the file read the file, I am writing the contents into another file in my next '.then' block. Once the contents are written into a file I need log a message. I have included that in the second '.then' block. I need to know whether my understanding is correct on promises. will the second '.then' block works as the callback function for writefile statement?
I need to write more meaningful log messages. Different error messages if an error occurs while reading the file and writing the file. How can I do this with catch blocks?
Thanks in advance!
The code example is below.
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));
var logger = require("./logger.js")
var projectJSON = require("../project.json");
var harPath = projectJSON.project.harfile.location;
var harFileNames = projectJSON.project.transactions.transactionsName;
var harFilePath;
var harFiles = {};
var writeFilePath = "../temp/"
harFileNames.forEach(function(harFileName){
harFilePath = harPath + "/" + harFileName + ".har";
fs.readFileAsync(harFilePath, "utf-8")
.then(function(data){
fs.writeFile(writeFilePath + harFileName + ".json", data);
test = data;
})
.then(function(){
console.log("data written successfully: ");
})
.catch(function(err){
logger.error("error", "Error reading har files from location!");
});
});