Nodejs Plotly - How To Wait For Getimage To Finish Before Continuing
Solution 1:
Welcome to Stack Overflow!
I have removed my previous answers, because (as you correctly pointed out) they didn't solve the full problem.
There are two asynchronous tasks that need to complete before we return control outside of the generate_plot()
function: retrieving data from Plotly, and writing that content to disk.
The example below calls generate_plot()
, and then (as a test to validate whether the file is really on disk) it immediately copies test.png
to test2.png
. Because this results in both files being the same size, this demonstrates that the fs.copyFileSync
is not running until the test.png
file is fully on disk.
I did change some of your variable names slightly, but this should work now.
For waiting for the file stream to finish, I reference this question: event associated with fs.createWriteStream in node.js
functiongenerate_plot() {
returnnewPromise((resolve, reject) => {
var trace = {
type: 'bar',
x: ['Mario', 'Luigi', 'Bowser'],
y: [50000, 10000, 2000],
marker: { color: ["red", "green", "darkblue"] },
};
var layout = {
plot_bgcolor: 'rgb(52, 54, 60)',
paper_bgcolor: 'rgb(52, 54, 60)',
};
var chart = { data: [trace], layout: layout };
var pngOptions = { format: 'png', width: 1000, height: 500 };
plotly.getImage(chart, pngOptions, (err, imageStream) => {
if ( err ) returnreject(err);
var fileStream = fs.createWriteStream('test.png');
imageStream.pipe(fileStream);
fileStream.on('error', reject);
fileStream.on('finish', resolve);
});
});
}
functionrun() {
generate_plot()
.then(() => {
fs.copyFileSync('test.png', 'test2.png');
console.log('done');
})
.catch(err => {
console.log(err);
});
}
Post a Comment for "Nodejs Plotly - How To Wait For Getimage To Finish Before Continuing"