So in my node js application i have a module structure like this.
Case 1:
server.js in which i call encrypt() function from other other module. In encrypt() function i call function from another module called zip(). when i run my server.js script zip() function successfully zip my file but not encrypt it correctly just make an encrypted file of 34kb. And i am unable to decrypt my files then.
Case 2:
In this case i first zip my file using zip() function then pass the created ziped file to encrypt() function this successfully zip my files. After that i can decrypt it successfully.
encrypt.js
const fs = require('fs')
const encryptFiles = require('./encryptFiles')
const removeZip = require('./removeZip')
const removeFolder = require('./removeFolder')
const zip = require('./zip')
const algorithm = 'aes-192-cbc';
const password = 'saad123';
async function encrypt(selectedDir){
let dirName = selectedDir.substring(selectedDir.lastIndexOf('/') + 1, selectedDir.length);
let arr = await zip(dirName) // generate a compress file and return name
let filename = arr[0]
let encryptTo = arr[1].concat('.enc')
fs.readFile( filename , async (err,file) => { // can we read zip file?
if(err) return console.log(err.message)
let encrypted = await encryptFiles(algorithm,password,file);
fs.writeFile('./key',encrypted[1], (err,file) => {
if(err) return console.log(err.message)
})
fs.writeFile(encryptTo,encrypted[0], (err,file) => {
console.log('encrypted',encrypted[0]);
if(err) return console.log(err.message)
if(file){
console.log('encrypt success!');
}
})
})
}
module.exports = encrypt
zip.js
const fs = require('fs')
const archiver = require('archiver');
function zip(dirName){
let name = dirName;
dirName = dirName.concat('.zip');
console.log(name,dirName);
const output = fs.createWriteStream(dirName);
const archive = archiver('zip', {
zlib: { level: 9 } // Sets the compression level.
});
output.on('close', () => {
console.log(archive.pointer() + ' total bytes');
});
archive.on('error', (err) => {
throw err;
});
archive.pipe(output);
archive.directory(name, false);
archive.finalize();
console.log('zipped');
return [dirName,name]
}
module.exports = zip