node.js - 使用 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'
}
}
}
我也试过这段代码,但它输出同样的错误。
解决方案
它在删除 json 后工作:req.body
我的错。
推荐阅读
- c# - 为什么我们仍然可以使用已处置的对象?
- java - 将 Gluon UI 库添加到 JavaFX 桌面应用程序
- c# - 使用 C# Nullable 引用类型将外部 dll 中的所有类型视为可为空的
- java - 无法使用 EditText Android 添加像 0.25 这样的小数
- plsql - 通过触发器-PLSQL 获取新插入的记录时出错
- clojure - 在 ClojureScript 中序列化 JavaScript 对象
- javascript - Rails 6 加载所需的自定义 JS,但这些功能都不起作用
- css - 我们可以在 react native 中使用 rems 来设置组件的样式吗
- google-assistant-sdk - 如何使用 Google Assistant 中的“Fulfillment URL”在响应中获取 language_code
- android - 在准确的时间使用 Job Scheduler 执行后台任务