【问题标题】:Nestjs readFileSync return Cannot read property 'readFileSync' of undefinedNestjs readFileSync返回无法读取未定义的属性'readFileSync'
【发布时间】:2021-05-18 16:59:40
【问题描述】:

我尝试使用 readFileSync 方法获取文件:

import fs from 'fs';
import path from 'path';

const templateFile = fs.readFileSync(
    path.resolve(
    __dirname,
    '../mail/templates/exampleTemplate.html',
    ),
    'utf-8',
);

Nest 仍然返回错误:

TypeError:无法读取未定义的属性“readFileSync”

我尝试过使用路径:./templates/exampleTemplate.html,但结果是一样的

我有一个结构文件:

【问题讨论】:

  • 您如何需要fs 模块?可以分享require语句的代码吗?
  • import fs from 'fs';
  • @ArunKumarMohan 您的查询很有帮助,我将import 更改为require,现在文件可以正常工作了。谢谢;)
  • 不客气。您可以使用import,但它必须使用不同的语法。我已经在回答中解释过了。

标签: node.js nestjs readfile


【解决方案1】:

由于您使用的是 Typescript 并且 fs 没有默认导出,因此您必须使用 import * as fs from 'fs'

【讨论】:

    【解决方案2】:

    试试

    import {readFileSync} from 'fs'
    

    【讨论】:

      【解决方案3】:

      我通过改变来修复它:

      import fs from 'fs';
      import path from 'path';
      

      到:

      import fs = require('fs');
      import path = require('path');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-12
        • 2021-02-27
        • 2021-10-30
        • 2020-06-26
        • 2021-07-23
        • 2020-08-28
        • 2020-05-12
        • 2020-11-10
        相关资源
        最近更新 更多