在for循环节点js中使用fs writeFile

时间:2018-07-13 12:00:21

标签: node.js filesystems

我需要使用fs.writeFile将数组中的每个base64字符串转换并写入不同的文件,但是仅保存最后一个数组元素。在下面看看我的代码:

let receivedData =["iVBORw0KGgoAAAANSUhEUgAABM...", "4AAANiCAYAAACZ8IVOAAAKqGlDQ1BJQ0MgU..."]:


//decode base 64 to buffer

let decodeBase64 = (dataArray) => {
let result = [];

dataArray.forEach((element) => {
  result.push(Buffer.from(element, 'base64')); 
 })
 return result; //array
};

let writeFileAsync = (data) => {
  let filename = Date.now() + '.jpeg';
  return new Promise((resolve, reject) => {
    data.forEach((value) => {
     fs.writeFile(filename, value, (err) => {
      if(err){
       reject(err);
      } else {
       console.log('file is saved');
       resolve(value);
      }
    })
  })
 }

let decoded = decodeBase64(receivedData);

writeFileAsync(decoded)
.then((result) => {
 console.log('file is saved');
})
.catch((error) => {
 console.log(error);
})

receivedData的最后一个值保存到文件系统,但不保存第一个元素 我知道这与在循环中执行异步方法有关,也许还有其他事情。循环只是在写文件完成之前增加。

任何帮助/提示都将不胜感激

1 个答案:

答案 0 :(得分:0)

尝试一下,它将一步一步地上传您的文件,这会花费一些时间,但是会给您带来合适的结果:

   let fileUpload = async (FILES , PATH, CB)=>{
        /** image Path **/
        let lengthOfFiles = FILES.length, RETURN_IMAGEPATHS = [], count = 0, 
        uploadFunc= [];
        for(let index= 0; index < lengthOfFiles; index++){
                let name = Date.now() + ".png";
                RETURN_IMAGEPATHS.push('http://localhost:3000/' + <PATH_FOR_FILE> + name);
                uploadImage(<Image save path>, <Imagte file path>, FILES[index]);
        }

        CB(null, RETURN_IMAGEPATHS);
    };

function uploadImage(imageSavePath, filePath, FILE){
    return new Promise(async (resolve, reject)=> {

        await fs.writeFileSync(imageSavePath, FILE, "base64", function (err) {
            if (err)
                reject(err);
            else {
                filePath ='http://localhost:3000/' + filePath;
                resolve(filePath);
            }
        });
    })
}

fileUpload(FILES , PATH, (err)=>{
  if(err){
    console.log(err);
  }
   else
  console.log('Success');
})