0

I am trying to create files (pdf, images, videos) from binary string stored in SQLite DB. The DB was created using a legacy PHP application and the file columns were all generated by simply inserting the result of file_get_contents() to the db.

Now, I am trying to create the file from these string values:

fs.promises
          .mkdir(path.dirname("tmp/" + file.file_path), {recursive: true})
          .then(x => fs.promises.writeFile("tmp/" + file.file_path, file.file_chunk));

Where file_path is the full path of the file and file_chunk is the binary string (result of file_get_contents).

When I run the PHP code on the same DB values, file_put_contents() gives me a correct file, however, the output of the above code in Node.js produces blank pdf or corrupt image files.

Is there a way to write files in nodeJS using the result of PHP's file_get_contents()?

Community
  • 1
  • 1
gentrobot
  • 673
  • 6
  • 25
  • You need to specify the encoding type in `writeFile` as 'binary' .something like `fs.promises.writeFile("tmp/" + file.file_path, file.file_chunk,'binary')` – jenil christo Mar 05 '19 at 15:52
  • Yes, I have tried that too, didn't work. Even after specifying encoding type as binary or utf8, the files are not written correctly. – gentrobot Mar 05 '19 at 16:07
  • It was indeed an encoding issue. I used mb_detect_encoding() at PHP and npm detect-character-encoding for node to check the encoding of the input and output. Turned out that the encoding was windows-1252. Then I used the windows-1252 npm module and https://stackoverflow.com/questions/42414839/convert-windows-1252-to-utf-8-with-js to solve my problem – gentrobot Mar 09 '19 at 04:16

0 Answers0