【问题标题】:fs.readDirSync can't find dir in typescript?fs.readDirSync 在打字稿中找不到目录?
【发布时间】:2019-10-29 19:54:41
【问题描述】:

这是一个非常简单的,我希望从 js 中工作:

import * as fs from 'fs';
var testDir = './tests';

// Add each .js file to the mocha instance
fs.readdirSync(testDir)
  .filter(function(file) {
    // Only keep the .js files
    return file.substr(-3) === '.js';
  })
  .forEach(function(file) {
    mochaInstance.addFile(path.join(testDir, file));
  });

我正在运行此代码的转译版本,但这会引发错误:

错误:ENOENT:没有这样的文件或目录,scandir './tests' 在 Object.readdirSync (fs.js:783:3)

我该如何解决这个问题?我确定文件 './tests' 的目录是正确的,我的节点版本是 v10.13.0

【问题讨论】:

  • 标准函数不知道相对路径,建议使用__dirname + '/tests',否则可以使用path
  • 你只是在编译吗?还是你也在包装?您的任何代码是否与当前目录混淆,因为./ 是相对于当前工作目录的。

标签: node.js fs


【解决方案1】:

您必须使用 __dirname,它是 Node.js 中的全局变量,用于获取应用程序的当前目录。结合路径,你最终可能会使用这样的东西:

mochaInstance.addFile(path.join(__dirname, testDir, file));

【讨论】:

  • __dirname 实际上不是全局变量。它是一个模块变量,在每个模块中可能具有不同的值。
猜你喜欢
  • 1970-01-01
  • 2022-08-12
  • 2017-05-02
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
  • 2015-09-03
  • 2021-01-07
相关资源
最近更新 更多