場景:上傳圖片
注意: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); });
});
}
簡化示例版
const requestFunc = async () => {
let r = null
try {
r = await function_async()
} catch (e) {
console.error(e.message)
}
return r
}
return await requestFunc()
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();
