admin管理员组

文章数量:1399887

I am trying to save some data in a file using fs.writeFileSync, but it doesn't work and I cannot figure out why. It throws the following error: 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.

What might be the problem ?

I am trying to save some data in a file using fs.writeFileSync, but it doesn't work and I cannot figure out why. It throws the following error: 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.

What might be the problem ?

Share Improve this question edited Jan 30, 2021 at 19:50 Robert Bogos asked Jan 30, 2021 at 19:38 Robert BogosRobert Bogos 531 gold badge2 silver badges7 bronze badges 6
  • Did you require/import the fs module? If so, please add the import statement to the code snippet. – Amit Beckenstein Commented Jan 30, 2021 at 19:42
  • is this javascript you wrote supposed to run on a browser? if yes then I dont think it will work – Tch Commented Jan 30, 2021 at 19:53
  • Do you run the code in nodejs or do you use some packing tool such us webpack or rollup? Or do you run this in browser? Because browser does not have require nor access to fs. You can try do console.log(fs) and post the output. – Márius Rak Commented Jan 30, 2021 at 19:53
  • I run it in my browser with yarn run dev. Then how should I do this to make it work ? – Robert Bogos Commented Jan 30, 2021 at 20:00
  • This will never, ever run in a browser. – Wiktor Zychla Commented Jan 30, 2021 at 20:19
 |  Show 1 more ment

1 Answer 1

Reset to default 3

Import fs module like so:

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. In this case, fs evaluates to undefined, which caused the error when trying to invoke its in-existent function member.

本文标签: javascriptWhy does fswriteFileSync() throws quotis not a functionquot errorStack Overflow