Nodejs中async/await以及Promise的使用
作者:互联网
场景:上传图片
注意:try/catch是不能catch住Promise异步异常的
async uploadAction (req, res) { try { // 同步调用 await saveFileWithStream(filePath, fileData); // 这里的fileData是Buffer类型 } catch (err) { console.log(err.stack); } } /** * 使用Promise封装createWriteStream异步事件处理 * @param {String} filePath [文件路径] * @param {Buffer} readData [Buffer 数据] */ static saveFile(filePath, fileData) { return new Promise((resolve, reject) => { if (!fs.existsSync(filePath)) { fs.mkdirSync(filePath); } // 块方式写入文件 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); }); }); }
nodejs文件写入操作
const fs=require('fs'); const path=require('path'); let writeStream=fs.createWriteStream('./test/b.js',{encoding:'utf8'}); //读取文件发生错误事件 writeStream.on('error', (err) => { console.log('发生异常:', err); }); //已打开要写入的文件事件 writeStream.on('open', (fd) => { console.log('文件已打开:', fd); }); //文件已经就写入完成事件 writeStream.on('finish', () => { console.log('写入已完成..'); console.log('读取文件内容:', fs.readFileSync('./test/b.js', 'utf8')); //打印写入的内容 console.log(writeStream); }); //文件关闭事件 writeStream.on('close', () => { console.log('文件已关闭!'); }); writeStream.write('这是我要做的测试内容'); writeStream.end();
标签:fs,console,log,Nodejs,await,wstream,Promise,filePath,writeStream 来源: https://www.cnblogs.com/terrylin/p/12454269.html