node.js - להשתמש ב-fs ב-TypeScript


אני פשוט מנסה לקרוא קובץ באמצעות 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. האם יש דרך מיוחדת לכלול את fs ב-TypeScript?

תשובה #1

אני לא יכול לדמיין שום מקרה שבו תשתמש ב-fs בתוך קומפוננטת React. למרות שאתה יכול להשתמש ב-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 שלך, ודא שיש תלות ב-node

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

תשובה #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/