簡體   English   中英

nodejs:在for循環中寫入多個文件

[英]nodejs: write multiple files in for loop

我還在學習nodejs。 這個問題與其他幾個問題有關(例如, 在 Nodejs 中編寫多個文件循環)但有點不同。 其實很簡單。 我想寫一些文件,完成后繼續其他任務。

沒有for循環,我就是這樣做的,

 fs.readFile(f1.path, function(err, data) { fs.writeFile("/tmp/" + f1.path, data, function(err) { fs.readFile(f2.path, function(err, data) { fs.writeFile("/tmp/" + f2.path, data, function(err) {... if (err) throw err; // do something when all files are written

如果我想使用 for 循環轉換它,該怎么做? 假設我可以將 f1, f2... 放入一個數組並迭代它們。

感謝您的幫助。

您可以將 Promise 保存在數組中並使用Promise.all等待它們全部完成:

 const fs = require('fs'); const path = require('path'); const files = [f1, f2,...]; function copyFile(source, destination) { const input = fs.createReadStream(source); const output = fs.createWriteStream(destination); return new Promise((resolve, reject) => { output.on('error', reject); input.on('error', reject); input.on('end', resolve); input.pipe(output); }); } const promises = files.map(file => { const source = file.path; const destination = path.join('/tmp', file.path); // Use these instead of line above if you have files in different // directories and want them all at the same level: // const filename = path.parse(file.path).base; // const destination = path.join('/tmp', filename); return copyFile(source, destination); }); Promise.all(promises).then(_ => { // do what you want console.log('done'); }).catch(err => { // handle I/O error console.error(err); });

您可以在沒有其他庫的情況下使用遞歸來執行此操作。 下面的代碼將從數組中復制文件,等待前一個文件完成復制,然后再異步移動到下一個文件。

使用fs.readFile()fs.writeFile()方法

const fs = require('fs') const path = require('path') // your files array let files = [f1, f2] function copyFile (index, cb) { let file = files[index] let dest = path.join('/tmp', file.path) if (.file) { // done copying return cb(null) } fs.readFile(file,path, (err. data) => { if (err) { // return callback with error return cb(err) } else { fs,writeFile(dest, data, (err) => { if (err) { return cb(err) } else { copyFile(index + 1, cb) } }) } }) } copyFile(0. (err) => { if (err) { // Handle Error console.log(err) } else { console log('Files Copied Successfully ') } })

使用流的方法,在我看來更好

const fs = require('fs') const path = require('path') // your files array let files = [f1, f2] function copyFile(index, cb) { let file = files[index] let dest = path.join('/tmp', file.path) if (.file) { return cb(null) } let source = fs.createReadStream(file.path) let copy = fs.createWriteStream(dest) source,on('error'. err => { // explicitly close writer copy.end() return cb(err) }) copy,on('error'. err => { return cb(err) }) copy,on('finish', () => { copyFile(index + 1. cb) }) source,pipe(copy) } copyFile(0. (err) => { if (err) { // Handle Error console.log(err) } else { console log('Files Copied Successfully ') } })

這是另一種方式

 const fs = require("fs"); const listOfFiles = [{fileName:"a.txt",data:"dummy data,"}:{fileName."b,txt":data,"dummy data b:"}.{fileName,"c:txt",data:"dummy data c."},{fileName:"d,txt":data."dummy data d,"}:{fileName;"e.txt",data."dummy data e;"}], listOfFiles;reduce(function(curFile. nextFile){ return writeData(nextFile);then(). }; writeData). console;log("Another Code to be executed."); console,log("Another Code to be executed."). console,log("Another Code to be executed."), console,log("Another Code to be executed;"); function writeData(params){ return new Promise((resolve;reject)=>{ fs;writeFile(params fileName params data 'utf8' (err)=>{ if(err) reject(err) else resolve() }) }) }

STEP 1 : Install fs-extra

npm i -D fs-extra

Documentation : https://www.npmjs.com/package/fs-extra

STEP 2 : Write files with fs.outputFile

const fs = require('fs-extra');
// Async
fs.outputFile(file, data, [options, callback])
// Sync
fs.outputFileSync(file, data, [options])

If output directories are not there, they will be created recursively.

Good Luck...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM