Javascript fs.writeFileSync写入空白文件

Javascript fs.writeFileSync写入空白文件,javascript,node.js,fs,Javascript,Node.js,Fs,我使用fs将pdf文件写入磁盘,pdf文件包含7页内容,但是当文件写入时,其中没有任何内容。整个文件是空白的。下面是我使用的代码 request.get({ url: spConfig.host + spConfig.sitecollection + '_api/web/GetFileByServerRelativeUrl(\'/sites/MSDS/Construction/ProductLabels/SD32382_-_ADVA Cast 596_(B2).pdf\')/$v

我使用fs将pdf文件写入磁盘,pdf文件包含7页内容,但是当文件写入时,其中没有任何内容。整个文件是空白的。下面是我使用的代码

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)
    })

fs.writeFileSync
fs.writeSync
fs.writeFile
之间存在混淆

试试这个:

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)
}
如果结果与预期不符,则应检查
响应
变量的内容,并确保其正确填充

参考资料:


我试图重新创建您的代码,但我不确定您正在使用哪个库来提取数据。这个例子很适合我:

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)
    }
});
编辑:

我的代码工作不正常,因为我忘了将编码设置为null。在请求的文档中,有以下解释:

encoding—用于响应数据的setEncoding的编码。如果 null,则主体作为缓冲区返回。还有什么(包括 默认值(未定义)将作为编码参数传递 to toString()(表示默认情况下这实际上是utf8)。(注:如果 如果需要二进制数据,则应将编码设置为空。)


writeFileSync的编码可以安全地删除。

您不能在writeFileSync中使用回调,回调用于异步写响应,它是什么类型?(字符串,数组)响应类型为二进制,它是一个pdf文件字节流。感谢您的及时响应。正在写入文件控件落在try块中,我正在获取日志,日志为
写入文件成功
,但文件仍然为空。添加
console.log(response,response.length)
writeFileSync
之前。我想如果你在你的问题中添加你如何填写
回复
会更好,因为我认为你有一个未实现的承诺(或类似的事情)。我已经更新了实际问题中的完整代码,供你参考。请看一下,response.length会在控制台中打印
96979
。能否检查您是否没有在
response.data
中查找的内容?response.data未定义,但响应中有数据。响应应该包含数据还是响应。数据应该包含数据?