Jeet
Jeet

Reputation: 5659

fs.writeFileSync writing blank file

I am using fs for writing a pdf file to disk, the pdf file contains 7 pages which have contents, however when the file is getting written it doesn't have any content in it. The whole file is blank. Below is the code I am using for this

request.get({
        url: spConfig.host + spConfig.sitecollection + '_api/web/GetFileByServerRelativeUrl(\'/sites/MSDS/Construction/ProductLabels/SD32382_-_ADVA Cast 596_(B2).pdf\')/$value',
        headers: headers,
        json: true
    }).then(response => {
      console.log('Inside Success')
      // console.log(response)
      // let writeStream = fs.createWriteStream(__dirname+'/wsdl/attachment.pdf')
      console.log(response.length)
       try {
            fs.writeFileSync(__dirname+'/wsdl/attachment.pdf', response,'binary')
            console.log('File has been written successfully')
        } catch (err) {
            console.log('Error in writing file')
            console.log(err)
        }
    }).catch(err => {
        spResponseCount = spResponseCount + 1  
        reject(err)
    })

Upvotes: 4

Views: 6558

Answers (1)

Stefano
Stefano

Reputation: 5076

There's a mixup between the fs.writeFileSync, fs.writeSync and the fs.writeFile.

Try with this:

try {
    fs.writeFileSync(__dirname+'/wsdl/attachment.pdf', response);
    console.log('Success in writing file')
} catch (err) {
    console.log('Error in writing file')
    console.log(err)
}

If the result is not what you expect, you should give a check to the content of the response variable and make sure that it's properly filled.

References:

https://nodejs.org/docs/latest-v8.x/api/fs.html#fs_fs_writefile_file_data_options_callback https://nodejs.org/docs/latest-v8.x/api/fs.html#fs_fs_writefilesync_file_data_options


I've tried to recreate your code but I'm not sure what library you're using to extract data. This example works fine with me:

let request = require('request-promise');
let fs = require('fs');

request.get({
    url: 'http://che.org.il/wp-content/uploads/2016/12/pdf-sample.pdf',
    encoding: null
})
.then(response => {

    try {
      fs.writeFileSync(__dirname+'/attachment.pdf', response);
      console.log('Success in writing file')
    } catch (err) {
      console.log('Error in writing file')
      console.log(err)
    }
});

EDIT:

My code was not working properly because I forgot to set the encoding to null. In the documentation of the request, there's this explanation:

encoding - encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer. Anything else (including the default value of undefined) will be passed as the encoding parameter to toString() (meaning this is effectively utf8 by default). (Note: if you expect binary data, you should set encoding: null.)

From https://www.npmjs.com/package/request#request-options-callback

The encoding of the writeFileSync can be safely dropped.

Upvotes: 6

Related Questions