【问题标题】:NestJS Service returning all files in a directoryNestJS 服务返回目录中的所有文件
【发布时间】:2020-12-30 06:12:34
【问题描述】:

我正在使用 NestJS 中的一项服务来返回工作目录中的所有文件。 NestJS 是最新的,我的 Node 安装是 14.12.0。

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

import { Observable, of } from 'rxjs';

import * as fs from 'fs';

@Injectable()
export class FileService  {

    constructor(
        private Configuration:ConfigService     // This service is just to set the working directory, where I have files
    ) { }

    public GetFileListing(Directory?:string):Observable<string[]> {
        const Results:Array<string> = new Array<string>();
        

//      fs.readdir(Configuration.DataDirectory, (err, files) => {
        fs.readdir('/c/users/xxx/datafiles/./', (err, files) => {
            files.forEach( file => {
                console.log(file);
                Results.push(file);
            });
        });
        return of(Results);
    }
}

但是,该函数不会读取数据并返回文件列表,而是会产生错误:

[ExceptionHandler] Cannot read property 'readdir' of undefined

更改为硬设置路径不起作用,尽管我可以使用 VSCode 中的终端窗口并执行 ls /c/users/xxx/datafiles/./ 并获取我期望的文件列表。

更改为import * as fs from 'fs'; 可以消除错误。

【问题讨论】:

    标签: node.js nestjs


    【解决方案1】:

    我相信fs 模块使用命名导出而不是默认值,所以你需要这样做

    import * as fs from 'fs';
    

    而不是

    import fs from 'fs';
    

    【讨论】:

    • 我更改了代码。您的更改确实消除了未处理的异常,但该功能仍然无法正常工作。我发现了在节点 10 之后指出的示例,您不需要 import * as fs from 'fs'; 只需使用 import fs from 'fs';,但它似乎确实解决了部分问题。
    • 那么你现在遇到了什么错误?你只是没有返回你所期望的吗?您可能返回的结果太快了,如果是这种情况,那么您应该将 fs.readdir 包装在一个 observable 中,而不是将结果推送到一个数组并返回一个 observable 的结果
    • 我猜缺少数据是由于我用来显示第一个错误的简单循环。我可能需要将其移至 Promise 或 Observable 以便为实际数据读取留出时间。
    猜你喜欢
    • 2011-12-17
    • 2022-11-30
    • 2021-05-10
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多