Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

node.js - Use fs in typescript

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);

}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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) => {
        // ...
    })

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

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

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/**/*"
    ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...