0

i had try to test out an encryption stuff and im new to nodejs.

after several try and search over google, i unable to solve my problem. please help.

case: calling async method to encrypt data, however it return me with a Promise { <pending> }

im using npm openpgp

objective: return the ciphertext so i could use it for other purpose

my code as below: //execution.js

var tools = require('./tools');
console.log(tools.encrypt());

//tools.js

const openpgp = require('openpgp') // use as CommonJS, AMD, ES6 module or via window.openpgp
var fs = require('fs');
openpgp.initWorker({ path:'openpgp.worker.js' }) // set the relative web worker path

var pubkey = fs.readFileSync('public.key', 'utf8');
const passphrase = `super long and hard to guess secret` //what the privKey is encrypted with

module.exports = {
    encrypt:async () =>{
        const options = {
                message: openpgp.message.fromText('Hello, World!'),       // input as Message object
                publicKeys: (await openpgp.key.readArmored(pubkey)).keys, // for encryption
            }

            const encrypted = await openpgp.encrypt(options);
            const ciphertext = encrypted.data;

            fs.writeFile('message.txt',ciphertext ,'utf8', function (err) {
              if (err) throw err;
              console.log('msg written!');
            });

            return ciphertext;
    },
    decrypt: async function(){
                // your code here
            }
};

please help

zhang yu
  • 45
  • 1
  • 4

2 Answers2

3

Async Await is simply syntactic sugar for promises an async function returns a promise.

You can't use await at the top level. What you can do is:

(async () => {
    try {
        console.log(await tools.encrypt());
    } catch (e) {
        console.log(e);
    }
})();

// using promises

tools.encrypt().then(console.log).catch(console.log);

Mike
  • 587
  • 3
  • 6
-1
tools.encrypt().then(res => console.log(res))

this line from @mark meyer solve my problem.

i was trying to access the thing without have to declare the 'async' word and have access to the 'res' so i could use for other purpose

Thanks alot.

zhang yu
  • 45
  • 1
  • 4