I am trying to write a function that will read a file and depending upon success or failure in reading it will call the resolve or reject function. Below is the code that I have written.
let fs = require('fs');
const FILE_NAME = './assets/pies.json';
let pieRepo = {
get: function(resolve, reject) {
fs.readFile(FILE_NAME, function(err, data) {
if(err) {
reject(err);
}
else {
resolve(JSON.parse(data));
}
});
}
};
module.exports = pieRepo;
However when I run "npm start" it throws the below error
/workingdirectory/repos/pieRepo.js:12
resolve(JSON.parse(data));
^
TypeError: resolve is not a function
at /workingdirectory/repos/pieRepo.js:12:17
at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)
I am using version 16.11.0 of node.
CodePudding user response:
The issue you are facing is with the way you are trying to resolve promise. The Resolve & Reject Functions are available within Promise
let fs = require("fs");
const FILE_NAME = "YOUR PATH TO FILE";
let pieRepo = {
get: () => {
return new Promise((resolve, reject) => {
fs.readFile(FILE_NAME, (err, data) => {
if (err) {
return reject(err);
}
resolve(JSON.parse(data));
});
});
},
};
module.exports = pieRepo;
You can further read about Promise
CodePudding user response:
Resolve and reject are functions available in promises.
Replace your code with this:
let fs = require('fs');
const FILE_NAME = './assets/pies.json';
let pieRepo = {
get: () => {
return new Promise((resolve, reject) => {
fs.readFile(FILE_NAME, (err, data) => {
if (err) {
return reject(err);
}
resolve(JSON.parse(data));
});
});
},
};
module.exports = pieRepo;
Now, you can await the get
function.
If this were my project though, the code would look like this:
let fs = require('fs/promises');
const FILE_NAME = './assets/pies.json';
let pieRepo = {
get: async () => {
try {
const data = await fs.readFile(FILE_NAME);
return data;
} catch (err) {
throw new Error(err.message);
}
},
};
module.exports = pieRepo;
If you want to promisify fs.readFile
, you can, but promisified versions of fs
functions are available through fs/promises
.
CodePudding user response:
You have to use Promise, here is a very simple example:
test() {
return new Promise((resolve, reject) => {
if (1 === 1) {
resolve(true)
} else {
reject(false)
}
})
}