【问题标题】:fs.readFile() or fs.readFileSync() not a function exception but why?fs.readFile() 或 fs.readFileSync() 不是函数异常,但为什么呢?
【发布时间】: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',
})

但是,如果我提供 readFileSyncpath 参数作为原始字符串(如下所示),它会正常工作(分配值)。

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


【解决方案1】:

因为fs 没有默认导出,您需要像这样导入:

import * as fs from 'fs'

【讨论】:

    【解决方案2】:

    您正在混合使用 javascript 标准。

    如果您选择使用较旧的 javascript ES5 标准,那么您的代码应如下所示:

    var fs = require('fs');
    

    但是,如果您要使用较新的 ES6(及更高版本)标准,您可以像这样使用import statement

    import fs from 'fs';
    

    您似乎将两者结合起来,因此您的错误。

    注意: 因为fs 具有导出fs 模块的默认导出,所以您不需要import * as 语法。更详细的解释见this post

    【讨论】:

    • ES6 方式抛出:“fs__WEBPACK_IMPORTED_MODULE_3___default().readFileSync 不是函数”
    猜你喜欢
    • 2015-07-05
    • 2017-01-18
    • 2018-09-24
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多