【问题标题】:fs.writeFileSync writing blank filefs.writeFileSync 写入空白文件
【发布时间】:2017-11-21 21:54:02
【问题描述】:

我正在使用 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)
    })

【问题讨论】:

  • writeFileSync 中不能使用回调,回调是异步写入的
  • 回应,是什么类型的? (字符串,数组)
  • 响应是二进制类型,是pdf文件字节流。

标签: javascript node.js fs


【解决方案1】:

fs.writeFileSyncfs.writeSyncfs.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)
}

如果结果不是你所期望的,你应该检查response变量的内容,并确保它被正确填充。

参考资料:

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


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

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,主体作为缓冲区返回。其他任何东西(包括 undefined 的默认值)将作为编码参数传递 toString() (这意味着默认情况下这实际上是 utf8)。 (注:如果 你期望二进制数据,你应该设置编码:null。)

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

writeFileSync 的编码可以安全删除。

【讨论】:

  • 感谢您的及时回复。文件正在写入,控件位于 try 块中,我得到的日志为 Success in writing file,但是文件仍然是空白的。
  • writeFileSync 之前添加一个console.log(response, response.length);。我认为如果您在问题中添加如何填写response 会更好,因为我认为您的承诺未实现(或类似的东西)。
  • 我已经更新了实际问题中的完整代码供大家参考。请看一下,response.length 在控制台中打印96979
  • 您能否检查一下response.data 中是否没有您要查找的内容?
  • response.data 未定义,但响应中有数据。响应应该包含数据还是 response.data 应该包含数据?
猜你喜欢
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 2013-06-13
相关资源
最近更新 更多