Pie*_*ran 21 node.js 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`
});
}
[...]
Run Code Online (Sandbox Code Playgroud)
并在一个简单的功能中使用它:
verifyToken = (token) => {
console.log(this.fs);
let contents = this.fs.readFileSync('../utils/public.key', 'utf8');
console.log(contents);
}
Run Code Online (Sandbox Code Playgroud)
但这提出了一个Uncaught TypeError: _this.fs.readFileSync is not a function.是否有一种特殊的方式包含fs在Typescript中?
And*_*ena 47
第一.我无法想象你会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) => {
// ...
})
Run Code Online (Sandbox Code Playgroud)
在您的package.json文件上,确保对节点具有依赖性
"dependencies": {
"@types/node": "^7.0.5"
}
Run Code Online (Sandbox Code Playgroud)
这就是我的tsconfig.json文件的样子:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react",
"allowJs": true,
"typeRoots": [
"./node_modules/@types"
]
},
"include": [
"./db/**/*",
"./src/**/*"
]
}
Run Code Online (Sandbox Code Playgroud)
Shi*_*Sao 16
使用node -v 10.15.0和@types/node:
好像声明被改写了……
fs定义被声明为 amodule所以你应该这样做:
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"
]
}
}
Run Code Online (Sandbox Code Playgroud)
Raf*_*zao 12
最新的植入,可以导入方法。
import { readFile, writeFile } from 'fs/promises';
Run Code Online (Sandbox Code Playgroud)
并且直接使用...
// write
await writeFile('./file.json', content);
// read
const content = await readFile('./file.json');
Run Code Online (Sandbox Code Playgroud)
参考https://nodejs.org/docs/latest-v14.x/api/
| 归档时间: |
|
| 查看次数: |
38693 次 |
| 最近记录: |