首页 > 解决方案 > 使用 FS 读取文件时出现结束错误后写入

问题描述

我构建了一个程序,用户可以使用 PDF URL 发送请求,然后将其下载并转发到外部 API 端点。现在,代码能够下载文件,但是在开始读取文件时遇到了这个错误。

我必须承认 Promises 是我讨厌学习的东西,因此我将 Async Function 与 Awaits 一起使用,在其他情况下我使用普通函数。承诺太难把握了。语法使其难以阅读。

代码如下:

const fs = require('fs');
const url = require("url");
const path = require("path");
const http = require('http')
const rp = require('request-promise');
const app = express();
const port = 8999;


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/upload-invoice', (req, res) => {
  
  var parsed = url.parse(req.body.FileURL);
  var filename = (path.basename(parsed.pathname));
  var downloaded_file_path = `invoices/${filename}`;
  
  function download() {
    
    var options = {
      hostname: parsed.hostname,
      port: 2799,
      path: parsed.path,
      method: 'GET'
    }
    
    const file = fs.createWriteStream(`invoices/${filename}`);
    
    const make_request = http.request(options, (response) => {
      response.pipe(file);
    });
    
    make_request.end();
    
    try {
      setTimeout(function () {
        upload()
      }, 1000);
    } catch (error) {
      console.log('An Error occured when uploading file,'+error);
    }
    
  }
  
  async function upload() {
    
    const flow = "Upload Invoice"
    var file_stream = fs.createReadStream(downloaded_file_path)
    
    var options = {
      method: 'POST',
      strictSSL: true,
      uri: 'https://endpoint.goes.here',
      formData: {
        'file': file_stream
      },
      headers: {
        'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryzte28ISYHOkrmyQT'
      },
      json: req.body,
      resolveWithFullResponse: true
    }
    
    try {
      var response = await rp(options)
      res.send(response.body)
    }
    catch (error) {
      console.log(`An error on ${flow} flow for unknown user. Here is more info about error,
        ${error}
        `)
        res.send("Error")
      }
    }
    
    download()
  });
  
  app.listen(port)

更新:

      formData: {
        name: filename,
        file: {
          value: fs.createReadStream(downloaded_file_path),
          options: {
            filename: filename,
            contentType: 'application/pdf'
          }
        }
      }

我也试过这段代码,但它输出同样的错误。

标签: node.jsfsrequest-promise

解决方案


它在删除 json 后工作:req.body

我的错。


推荐阅读