在打字稿中使用 fs [英] Use fs in typescript

查看:56
本文介绍了在打字稿中使用 fs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm just trying to read a file using fs.readFileSync, though it seems it cannot be found.

我确保声明它,并将其添加到我的构造函数中:

I made sure to declare it, added it within my constructor:

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`
        });
    }
[...]

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

And used it in a simple function:

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 ?

But this raises an Uncaught TypeError: _this.fs.readFileSync is not a function. Is there a special way to include fs in Typescript ?

推荐答案

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

I can't imagine any case in which you would use fs inside a React component. Even though you can use React in the server to render stuff, the same code is supposed to run in the client, there's no way you can access fs in the client.

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

If you want to use fs in the server, this is an example:

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

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

On your package.json file, make sure to have a dependency on node

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

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

And this is how my tsconfig.json file looks like:

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

这篇关于在打字稿中使用 fs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆