I have a module, it is working great except that I am returning a value before a file write is finished.
The module is this:
exports.write_binary = function (options) {
//for converting file paths provided in UI
const { toSystemPath } = require('../../../lib/core/path');
//uuid package
const { v4: uuidv4 } = require('uuid');
//required for retrieving and saving file
const http = require('https');
const fs = require('fs');
//convert the user local_path provided in the API action to useable in the module
let path = toSystemPath(this.parseRequired(this.parse(options.local_path), 'string', 'fs.exists: path is required.'));
//evaluate the data binding for remoteURL
let remoteURL = this.parseRequired(options.file_url, 'string', 'parameter value is required.');
//generate uuid
let uuid = uuidv4(); // āØ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
//set the filename
let file_name = path + '/' + uuid;
//open up the stream for writing the file
const file = fs.createWriteStream(file_name);
async function fetchURL() {
await http.get(remoteURL, async function (response) {
response.pipe(file);
await new Promise((r, j) => {
file.on('close', r);
});
})
.on('error', function (err) { // Handle errors
fs.unlink(file_name); // Delete the file async. (But we don't check the result)
});
}
fetchURL();
return { "file_path": uuid };
};
I am attempting to retrieve a file from a URL and return the file name (currently a uuid) for use within standard Wappler actions.
I thought my async function fetchURL would block the return from happening until it was finished, but Iām clearly doing something wrong.
@patrick does this.exec help me here?
If itās not obvious, Node and async are very new to me!