我正在使用带有以下导入代码的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)
更长的代码片段如下所示。我怀疑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(...);**
发布于 2019-03-13 03:05:22
因为fs
没有默认的导出,所以您需要像这样导入:
import * as fs from 'fs'
发布于 2019-03-13 03:06:08
您正在混合javascript标准。
如果您选择使用较旧的javascript ES5标准,则您的代码应如下所示:
var fs = require('fs');
但是,如果要使用较新的ES6 (及更高版本)标准,则应按如下方式使用import statement:
import fs from 'fs';
你似乎把这两者结合起来了,所以你错了。
注意:因为fs
具有导出fs
模块的缺省导出,所以您不需要import * as
语法。有关详细说明,请参阅this post。
https://stackoverflow.com/questions/55128930
复制相似问题