首页 > 解决方案 > fs.readDirSync 在打字稿中找不到目录?

问题描述

这是一个非常简单的,我希望从 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:没有这样的文件或目录,在 Object.readdirSync (fs.js:783:3) 处的 scandir './tests'

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

标签: node.jsfs

解决方案


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

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

推荐阅读