【问题标题】:Use fs in typescript在打字稿中使用 fs
【发布时间】:2017-08-20 06:16:24
【问题描述】:

我只是尝试使用fs.readFileSync 读取文件,但似乎找不到。

我确保声明了它,并在我的构造函数中添加了它:

export default class Login extends React.Component<LoginProps, {}> {
    private webAuth: auth0.WebAuth;
    fs: any;

    constructor(props: any, context: any) {
        super(props, context);
        this.fs = require('fs');
        this.webAuth = new auth0.WebAuth({
            clientID: conf.auth0.clientId,
            domain: conf.auth0.domain,
            responseType: 'token id_token',
            redirectUri: `${window.location.origin}/login`
        });
    }
[...]

并在一个简单的函数中使用它:

verifyToken = (token) => {

    console.log(this.fs);
    let contents = this.fs.readFileSync('../utils/public.key', 'utf8');
    console.log(contents);

}

但这会引发Uncaught TypeError: _this.fs.readFileSync is not a function。有没有一种特殊的方法可以在 Typescript 中包含 fs

【问题讨论】:

  • 你的Login 组件是浏览器组件,对吧?你为什么要使用fs 模块?
  • 如果您使用的是 wepback,您可以使用 raw-loader 获取文件内容。

标签: node.js typescript


【解决方案1】:

我无法想象你会在 React 组件中使用 fs 的任何情况。即使您可以在服务器中使用 React 来渲染内容,但应该在客户端中运行相同的代码,您无法在客户端中访问 fs

如果你想在服务器中使用fs,这是一个例子:

import * as fs from 'fs';
import * as path from 'path';
fs.readFile(path.join(__dirname, '../../client/index.html'), 'utf8', (error, data) => {
        // ...
    })

在您的package.json 文件上,确保对节点有依赖

"dependencies": {
 "@types/node": "^7.0.5"
}

这就是我的tsconfig.json 文件的样子:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "allowJs": true,
        "typeRoots": [
            "./node_modules/@types"
        ]
    },
    "include": [
        "./db/**/*",
        "./src/**/*"
    ]
}

【讨论】:

  • fs,在我的例子中,用于打开包含 Auth0 公钥的文件,该公钥用于验证 jwt 令牌。我对 React 还是很陌生,感谢您的建议!
  • npm install @types/node 的命令为我做了。
【解决方案2】:

使用node -v 10.15.0@types/node

声明好像被改写了……

fs 定义被声明为module,所以你应该这样做:

import fs from "fs"; // Without star

编译:

var fs_1 = __importDefault(require("fs"));

const fs = require("fs"); 而不是require("fs").default;

加上星号,您将拥有fs.default.TheFunctionYouWant 而不是fs.TheFunctionYouWant

更好的方法是console.log(fs);查看导入的内容。

{
  "compilerOptions": {
    "typeRoots": [],
    "types": [
      "node"
    ]
  }
}

【讨论】:

    【解决方案3】:

    最新植入,可以导入方法。

    import { readFile, writeFile } from 'fs/promises';
    

    并直接使用...

    // write
    await writeFile('./file.json', content);
    
    // read
    const content = await readFile('./file.json');
    

    参考https://nodejs.org/docs/latest-v14.x/api/

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 2022-01-06
      • 2021-10-26
      • 2017-01-17
      • 2017-10-05
      • 2017-05-11
      • 2021-02-19
      • 2013-08-07
      • 2021-12-05
      相关资源
      最近更新 更多