[英]Node- Append file in Async function
我正在使用貓鼬在數據庫中查詢對象,並希望將每個對象寫入文件。 console.log顯示我從查詢中返回了我想要的數據,但是fs.append(./returned.json)創建的文件始終為空。 在異步函數中不可能這樣做嗎?
async function findReturned(){
try {
const returned = await Data.find({});
returned.forEach(function(file) {
returnedfiles = file.BACSDocument;
console.log(returnedfiles);
fs.appendFile('./returned.json', returnedfiles, 'utf-8', (err) => {
if (err) throw err;
});
});
process.exit();
} catch(e) {
console.log('Oops...😯😯😯😯😯😯😯');
console.error(e);
process.exit();
}
};
您不能將async
函數和函數與回調API混合使用,也不能在forEach
內調用乘法async
函數,您必須創建一個promise來完成鏈中所需的工作(請參見下面的示例中的reduce
函數)。
另一種方式-使用.map
,返回一個promise數組,然后使用
await Proimse.all(arrayOfPromises)
但是在這種情況下,文件中新數據的順序將與初始數組中的順序不同。
為此,您需要對fs.appendFile進行fs.appendFile
並調用函數的賦值版本
// add new import
const {promisify} = require('util');
// create new function with Promise API on existing Callback API function
const appendFile = promisify(fs.appendFile)
async function findReturned(){
try {
const returned = await Data.find({});
// Create a single promise that will append each record one by one to the file in initial order.
const promise = returned.reduce(function(acc, file){
returnedfiles = file.BACSDocument;
console.log(returnedfiles);
acc.then(() => appendFile('./returned.json', returnedfiles, 'utf-8'));
return acc
}, Promise.resolve());
// Wait until the promise resolves;
await promise;
process.exit();
} catch(e) {
console.log('Oops...😯😯😯😯😯😯😯');
console.error(e);
process.exit();
}
};
除了使用build int fs
模塊之外,您還可以使用fs-extra
模塊,該模塊已經具有本地方法的承諾版本和一些其他方法。
您可以在功能上進行的改進-不要追加文件乘法次數,而是將需要追加到文件的所有數據收集到單個變量中,然后執行一次。
如果由於某種原因必須將其乘以-使用fs.open
獲取文件描述符,並將其而不是文件名傳遞給fs.appendFile(或約定的版本)。 在這種情況下,請不要忘記關閉文件描述符( fs.Close
)。
您可能應該將mz / fs用於異步功能
const fs = require('mz/fs');
...
returned.forEach(async (file) => {
returnedfiles = file.BACSDocument;
await fs.writeFile('./returned.json', returnfiles, 'utf-8');
})
您不需要拋出錯誤,因為它會抓住問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.