简体   繁体   English

为什么 fs.writeFileSync() 会抛出“不是函数”错误?

[英]Why does fs.writeFileSync() throws “is not a function” error?

I am trying to save some data in a file using fs.writeFileSync, but it doesn't work and I cannot figure out why.我正在尝试使用 fs.writeFileSync 将一些数据保存在文件中,但它不起作用,我不知道为什么。 It throws the following error: Unhandled Rejection (TypeError): fs.writeFileSync is not a function它引发以下错误: Unhandled Rejection (TypeError): fs.writeFileSync is not a function

In my app I use it like this:在我的应用程序中,我像这样使用它:

const fs = require('fs');
const stateFile = "./usersStateFile";

const saveLastEventSequenceId = (sequenceId) => {
    try {
            fs.writeFileSync(stateFile, sequenceId);
        } catch (err) {
          throw err;
        }
     };

The sequenceId is a number and the ./usersStateFile doesn't exist, but fs.writeFileSync() should create it if it doesn't exist. sequenceId是一个数字并且./usersStateFile不存在,但fs.writeFileSync()应该在它不存在时创建它。

What might be the problem?可能是什么问题?

Import fs module like so:像这样导入fs模块:

const fs = require('fs'); // or `import * as fs from 'fs'` if you're using ES2015+
const stateFile = "./usersStateFile";

const saveLastEventSequenceId = (sequenceId) => {
  try {
    fs.writeFileSync(stateFile, sequenceId);
  } catch (err) {
    throw err;
  }
};

You were calling fs.writeFileSync() without having a variable named fs that's defined in your scope.您调用fs.writeFileSync()时没有在 scope 中定义的名为fs的变量。 In this case, fs evaluates to undefined , which caused the error when trying to invoke its in-existent function member.在这种情况下, fs评估为undefined ,这在尝试调用其不存在的 function 成员时导致错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM