@hyperbytes/wappler-text-to-file-with-encoding
Version:
Binary write file from text
34 lines (26 loc) • 1.37 kB
JavaScript
const fs = require('fs').promises;
const { toSystemPath } = require('../../../lib/core/path');
const path = require('path');
exports.text2file = async function (options) {
try {
// Parse required inputs
const isDebugMode = this.parseOptional(options.logging, "*", false);
const sourcetext = this.parseRequired(options.sourcetext, '*', 'No Source Text supplied');
const filepath = this.parseRequired(options.filepath, '*', 'No File Path supplied');
const filename = this.parseRequired(options.filename, '*', 'No File name supplied');
const encoding = this.parseOptional(options.encoding, '*', 'utf8');
isDebugMode && console.log("Encoding: " + encoding)
// Combine path and convert to system path
// Combine and normalize path
const localPath = path.posix.join(filepath, filename); // Ensures forward slashes
const resolvedPath = toSystemPath(localPath);
isDebugMode && console.log('FilePath:', resolvedPath);
// Write the text to the file
await fs.writeFile(resolvedPath, sourcetext, encoding);
isDebugMode && console.log('File written successfully!');
return { status: 200, path: resolvedPath };
} catch (error) {
console.error('Error writing file:', error);
return { status: 400, path: error.message };
}
};