javascriptnode.jsbase64fsmultiparty

Can't read file after writing it with fs


I want to read an image ,write it in a folder and read it again to get it's base64 I get the following error: Error: ENOENT: no such file or directory, access 'C:\Workspace\Project\upload_storage\image.jpg' at Object.accessSync (fs.js:192:3)

My code:

const FS = require("fs");
var multiparty = require('multiparty');
var path = require('path');
function readAndWriteFile(file , newPath){
  FS.readFileSync(file.path, (err, data)=>{
      FS.writeFileSync(newPath, data, (err)=>{                                                                                                                
          });
  });
}
function base64Encode(path,filemime) {
    FS.readFileSync(path, {encoding: 'base64'}, (err, data)=>{
      if (err) {
        throw err;
      }
      return `data:${filemime};base64,${data}`;
    });
}

...

          var form = new multiparty.Form()
          //retrieve files using multiparty form
          form.parse(req, function(err, fields, files) {
            var document;
            const documents = files.file; 

            for(i=0; i<documents.length; i++){
              document=documents[i];
              const contentType = String(document.headers["content-type"]);
              filePath = path.join(process.cwd(),'/upload_storage/',document.originalFilename);
              readAndWriteFile(document,filePath);
              // // convert image to base64 encoded string
              const base64str = base64Encode(filePath, contentType);
              console.log(base64str);
            }
         }

if I comment the base64Encode function call the files get created. What am I doing wrong?


Solution

  • Don't use callbacks with _fileSync. But it looks like you want copyFileSync followed by unlinkSync anyway:

    const fs = require('fs');
    
    function readAndWriteFile(file , newPath){
      fs.copyFileSync(file.path, newPath);
      fs.unlinkSync(file.path)
    }
    

    Did you try reading the documentation for fs?

    More reading and examples in this question,