Nodejs the async / await Promise and the use of

Scene: upload pictures

Note: try / catch can not catch live asynchronous exception of Promise

Other: Nest.js upload images and cropping

uploadAction the async (REQ, RES) { 

  the try { 
   // synchronous call 
   await saveFileWithStream (filePath, fileData); // fileData here is the type of Buffer 
  } the catch (ERR) { 
   the console.log (err.stack); 
  } 

} 


/ ** 
 * Promise using asynchronous event handling package createWriteStream 
 * @param {String} filePath [file path] 
 * @param {Buffer} readData [Buffer data] 
 * / 
static the saveFile (filePath, fileData) { 

  return new new Promise ((Resolve, Reject) = > { 

  IF {(fs.existsSync (filePath)!) 
   fs.mkdirSync (filePath); 
  } 

  // block write to files 
  const = wstream fs.createWriteStream (filePath); 
 
  wstream.on ( 'Open', () => { 
   const blockSize = 128;
   const nbBlocks = Math.ceil(fileData.length / (blockSize));
   for (let i = 0; i < nbBlocks; i += 1) {
    const currentBlock = fileData.slice(
     blockSize * i,
     Math.min(blockSize * (i + 1), fileData.length),
    );
    wstream.write(currentBlock);
   }
 
   wstream.end();
  });
  wstream.on('error', (err) => { reject(err); });
  wstream.on('finish', () => { resolve(true); });
 });
}

 

A simplified example version

const requestFunc = async () => {
    let r = null
    try {
      r = await function_async()
    } catch (e) {
      console.error(e.message)
    }
    return r
}
 
return await requestFunc()

 

nodejs file write operations

 
the require FS = const ( 'FS'); 
const = path the require ( 'path'); 
the let writeStream = fs.createWriteStream ( './ Test / b.js', {encoding: 'UTF8'}); 
 
 
// read file error event occurs 
writeStream.on ( 'error', (ERR) => { 
    the console.log ( 'abnormal:', ERR); 
}); 
// open file event to write 
writeStream.on ( 'open ', (FD) => { 
    the console.log (' open file: ', FD); 
}); 
// file has been written on completion event 
writeStream.on (' Finish ', () => { 
    the console.log ( 'writing has been completed ..'); 
    the console.log ( 'read file content:', fs.readFileSync ( './ test / b.js', 'utf8')); // print the written content 
    the console.log (writeStream); 
}); 
 
// close file event 
writeStream.on ( 'close', () =>{ 
    The console.log ( 'file is closed!'); 
});
 
writeStream.write ( 'This is what I have to do the test content'); 
writeStream.end ();
 
 
 

  

 

Guess you like

Origin www.cnblogs.com/terrylin/p/12454269.html
Recommended