fs.readFileSync(filePath, function read(err, data) {} 即使目标文件位于正确位置也不起作用

fs.readFileSync(filePath, function read(err, data) {} does not work even tho the targeted file is in the correct location

这是我的相关代码:

1)

 let pickenFile = randomItemFormatted.source_filenametxt;
 let filePath =  `textFiles/${pickenFile}`;

这发生在axios.get() returns 文件名之后。 问题不在于文件本身的名称。

2)

     fs.readFileSync(filePath, function read(err, data) {
       if(err){
         console.log(err);
         runTheBot();
       }else{

          // I should be able to access the data here :(        
          console.log(data);

         tokenizer = new natural.SentenceTokenizer();
         let textToTokenize = tokenizer.tokenize(data.toString('utf8').replace(/[=12=]/g, ''));
         dataObj.randomItemFormatted = randomItemFormatted;
         dataObj.stringsArray = textToTokenize;
         return returnSpecificString(dataObj);
       }
    });
  })}

当我将文件路径传递给 fs.readFileSync() 时,代码没有传递 error 块。我在这里添加完整的错误响应:

(node:9500) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open 'textFiles/1884_Ford__Bradstreet.txt'
    at Object.openSync (fs.js:447:3)
    at Object.readFileSync (fs.js:349:35)
    at /Users/cyrus/Documents/Code/01. Code/franklin-ford-bot/server_side/server.js:74:9
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:9500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这也是我的项目架构,其中目标 .txt 文件是 hosted.I 使用 node server_side/server.js.

启动服务器

它之前工作正常,并且自工作以来代码没有任何变化。

fs.readFileSync() 不接受回调。您的代码正在尝试将 fs.readFile() 接口与 fs.readFileSync() 结合使用。参见 the doc

来自 fs.readFileSync() 的错误将作为异常抛出,因此您需要 try/catch 围绕它来捕获错误。

在您显示的代码中使用 fs.readFileSync() 的一般结构如下所示:

try { 
    let data = fs.readFileSync(filePath);
    // I should be able to access the data here :(        
    console.log(data);

    tokenizer = new natural.SentenceTokenizer();
    let textToTokenize = tokenizer.tokenize(data.toString('utf8').replace(/[=10=]/g, ''));
    dataObj.randomItemFormatted = randomItemFormatted;
    dataObj.stringsArray = textToTokenize;
    return returnSpecificString(dataObj);
} catch(e) {
    console.log(e);
    runTheBot();
    return something;
}

现在,关于 ENOENT 错误,这是一个需要解决的单独问题。我建议您这样做:

const path = require('path');

let filePath =  `textFiles/${pickenFile}`
console.log(path.resolve(filePath));

这将显示您尝试使用的文件的完整路径。很可能是完整路径与您预期的不完全相同,或者存在文件权限问题阻止您访问它。


如果您尝试访问的 textFiles 子目录位于此代码 运行 所在的模块目录下,那么您可能希望使用 __dirname 来引用它,如下所示:

const path = require('path');
let filePath = path.join(__dirname, "textFiles", pickenFile);