Use fs in typescript

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

I made sure to declare it, added it to 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 causes an Uncaught TypeError: _this.fs.readFileSync is not a function . Is there a special way to include fs in Typescript?

+18
source share
2 answers

First. I can not imagine a single case where you would use fs inside the React component. Although you can use React on the server for rendering, the same code should be executed on the client, but you have no way to access fs on the client.

If you want to use fs on 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) => { // ... }) 

Make sure your package.json file has a node dependency

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

And here is my tsconfig.json file:

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

Using node -v 10.15.0 and @ types / node :

It seems the declaration has been rewritten ...

The definition of fs declared as module , so you should do:

import fs from "fs"; // Without star

compiled by:

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

or

const fs = require("fs"); instead of require("fs").default;

with an asterisk you will have fs.default.TheFunctionYouWant instead of fs.TheFunctionYouWant

Best of all console.log(fs); see what exactly is being imported.

 { "compilerOptions": { "typeRoots": [], "types": [ "node" ] } } 
+1
source

Source: https://habr.com/ru/post/1265962/


All Articles