【问题标题】:File is not defined : when create File Object with typescript文件未定义:使用打字稿创建文件对象时
【发布时间】:2021-09-04 05:10:24
【问题描述】:

我在 node js(不是 API 或 Web 应用程序)中编写了一个带有 typescript 的程序,只是一个控制台应用程序。我已经配置了打字稿配置。但是当我创建一个文件对象时它给了我错误

UnhandledPromiseRejectionWarning: ReferenceError: File is not defined

My Code
// .......
var file = new File(["asdasdsa"], 'metadata.json');
console.log(file.name);
// ......

ts 配置 json 内容

    {
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "declaration": true,
    "strict": true,
    "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
    "strictNullChecks": true /* Enable strict null checks. */,
    "strictFunctionTypes": true /* Enable strict checking of function types. */,
    "noUnusedLocals": true /* Report errors on unused locals. */,
    "noUnusedParameters": true /* Report errors on unused parameters. */,
    "noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
    "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
    "importHelpers": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "outDir": "./dist/tsc/",
    "types": [
      "node",
      "jest"
    ],
    "lib": [
      "ES6",
      "DOM"
    ]
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "**/*.test.ts"
  ]
}

我在 typescript 配置中遗漏的任何内容。 我想用打字稿制作一个 File 对象

【问题讨论】:

  • 我也有同样的问题。运行 ts-node
  • node.js 没有实现 File 类(或 FileList 等)。有一些模块可以模拟它,但在服务器端,无论您使用 TS 还是 JS,这都不是仅使用节点的选项。
  • 我可以使用哪个模块来完成这项工作。 @乔谢谢
  • github.com/abrwn/get-file-object-from-local-path 可能这行得通,会试试

标签: node.js typescript file tsconfig


【解决方案1】:

在nodejs中,你没有File类型,但是你也可以使用fs来创建一个

类似这样的:

var fs = require('fs');

fs.writeFile('metadata.json', 'asdasdsa', function (err) {
  if (err) throw err;
});

这将在您的根文件夹中创建一个文件。

您可以像这样阅读并发送:

fs.readFile("./metadata.json", (err, data) => {
  if (err) res.status(500).send(err);
  res
    .contentType("application/pdf")
    .send(
      `data:application/pdf;base64,${new Buffer.from(data).toString("base64")}`
    );
});

【讨论】:

  • 我不想写文件。我想将文件对象传递给外部端点。我想读取文件并将其作为文件对象。 JS readFile 只是返回 Buffer 数组,而不是包含名称、大小等的 FIle 对象。
  • 啊,所以您想通过请求将文件发送给客户端。我更新了答案以匹配它。看看有没有帮助。
  • 我不需要传递响应,因为我的控制台应用程序没有被调用。我会将我的本地文件传递给一个外部 API,它是文件类型中所需的文件。但是当我从 JS 读取文件时,它会返回缓冲区数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-29
  • 1970-01-01
  • 2017-02-20
  • 2018-02-04
  • 2018-01-06
  • 2018-03-04
相关资源
最近更新 更多