【发布时间】:2021-06-29 21:42:37
【问题描述】:
我正在使用带有以下导入代码的fs 模块
import fs = require('fs')
代码一直运行,直到在下面的 TypeScript 代码的第二行遇到此异常
const filePath = 'data/soylent-uist2010/userSegments.json'
const seg = fs.readFileSync(filePath, {
encoding: 'utf8',
})
但是,如果我提供 readFileSync 的 path 参数作为原始字符串(如下所示),它会正常工作(分配值)。
const seg = fs.readFileSync('data/soylent-uist2010/userSegments.json', {
encoding: 'utf8',
})
错误堆栈跟踪如下,
Viewer.tsx:155 Uncaught (in promise) TypeError: fs.readFileSync is not a function
at Viewer.<anonymous> (Viewer.tsx:155)
at step (io.ts:106)
at Object.next (io.ts:106)
at io.ts:106
at new Promise (<anonymous>)
at __awaiter (io.ts:106)
at Viewer._this.loadFiles (Viewer.tsx:135)
at Viewer.<anonymous> (Viewer.tsx:98)
at step (io.ts:106)
at Object.next (io.ts:106)
更长的代码sn-p如下。我怀疑async 关键字(在类方法中)是否需要在fs.readFile() 之前使用await 关键字
loadFiles = async () => {
this.setState({ pages: [] });
const {
pageNumbersToLoad,
pathInfo: { pdfDir, pdfRootDir }
} = this.props;
const fullDirPath = path.join(pdfRootDir, pdfDir);
const pdfPath = path.join(fullDirPath, pdfDir + ".pdf");
**const seg = fs.readFile(...);**
【问题讨论】:
-
仅供参考 - 'fs' 用于文件系统,这意味着它只能在 Node.js 环境中工作,而不能在网站中工作。
-
import fs = require('fs')这不是 SyntaxError 吗?试试const fs = require("fs")或import * as fs from "fs"; -
谢谢你!想补充一下,所有的代码都在一个类函数中,可能不适合声明
filePath? -
感谢 Steven 和 Jonas,该项目位于 Parcel + TypeScript (es5) 中。我对前端开发非常陌生,所以不确定它是否是 Node.js 环境。
-
@XinQian 这取决于你在哪里使用它。它可以在构建步骤中使用,因为您使用 Node.js 构建,但它不能用于为网站捆绑的客户端代码中。
标签: javascript node.js typescript