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
thefs
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
1 Answer
Reset to default 3Import 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744244640a4564866.html
评论列表(0条)