Friday 5 May 2017

Why fs.readFileSync returns nothing inside a promise on serveside?

I found this "Rendering PDFs with React components" tutorial on themeteorchef about creating PDF files on Meteor serverside and then sending them back to client. I had no really need for PDF files, but docx files instead and thought that maybe I could follow similar approach when creating docx files with officegen

I created very similar server side module that generates a docx file from inputs on clientside and then tries to transform them into base64 string that is then supposed to be sent to the client. However, the base64 string is never created.

Here's the module:

let myModule;

const getBase64String = (loc) => {
  try {
    const file = fs.readFileSync(loc);
    return new Buffer(file).toString('base64');
  } catch (exception) {
    myModule.reject(exception);
  }
}

const generateBase64Docx = (path, fileName) => {
  try {
    myModule.resolve({fileName, base64: getBase64String(path+fileName)});
    fs.unlink(loc);
  } catch (exception) {
    myModule.reject(exception);
  }

}

const formatComponentAsDocx = (props, fileName) => {
  try {
    var docxFile = officegen({
      'type': 'docx',
      'orientation': 'portrait',
      'title': props.title,
    });

    var pObj = docxFile.createP();
    pObj.addText(props.body);

    var path = './';
    output = fs.createWriteStream(path+fileName);

    docxFile.generate(output);
    return path;

  } catch (exception) {
    myModule.reject(exception);
  }

}

const handler = ({props, fileName}, promise) => {
  myModule = promise;
  const path = formatComponentAsDocx(props, fileName);
  if (path) {
    generateBase64Docx(path, fileName);
  }
}

export const generateComponentAsDocx = (options) => {
  return new Promise((resolve, reject) => {
    return handler(options, { resolve, reject });
  });
};

The problem here is the fs.readFileSync part. It always returns empty buffer and that's why the file is never transformed into base64 string and also never sent back to client. Why's that? The file itself is always created on the server and can always be found.

If I change the const file = fs.readFileSync(loc); part to for example this

fs.readFile(loc, (err, data) => {
 if(err) myModule.reject(err);
 console.log(JSON.stringify(data));
}

I can see some data in data, but not enough for the whole file.

What am I doing wrong here? Am I missing something?



via zaplec

No comments:

Post a Comment