I want to send the data in res.send(data). When i
console.log("This dox data",text);
in terminal, it works fine. It logs all text content in terminal. But accessing at frontend it gives me error
router.get("/api/emailtemplates/data/:subject", (req, res) => {
Email_templates.find({subject: req.params.subject}, (err, data) => {
if (!err) {
const val = data[0]['template_file_link'];
console.log(val);
const data= textract.fromFileWithPath(val, function( error, text ) {
console.log("This dox data",text);
});
res.send(data);
} else {
console.log(err);
}
});
CodePudding user response:
That code will give you the error Uncaught ReferenceError: Cannot access 'data' before initialization
. You're trying to use the data
constant you've declared within the if (!err)
block before that constant has been initialized, because you've used data
both as the name of the parameter you're going to receive the data from Email_templates.find
in and also as the constant you store the result of textract.fromFileWithPath
in. Here's a simpler example of the problem:
function example(err, data) {
// ^^^^−−−−−−− parameter called `data`
if (!err) {
const val = data[0]['template_file_link'];
// ^^^^−−−−−−−−− ReferenceError here
// because this is trying to use
// the constant below before it's
// initialized (it's in the "Temporal
// Dead Zone")
const data = "whatever";
}
}
example(null, [{template_file_link: ""}]);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Use different names for them. For instance:
router.get("/api/emailtemplates/data/:subject", (req, res) => {
Email_templates.find({subject: req.params.subject}, (err, data) => {
if (!err) {
const val = data[0]['template_file_link'];
console.log(val);
const fileData = textract.fromFileWithPath(val, function( error, text ) {
// ^^^^^^^^
console.log("This dox data",text);
});
res.send(fileData);
// ^^^^^^^^
} else {
console.log(err);
}
});
});
CodePudding user response:
what is textract? you were trying to return wrong thing you need to send response in callback of the textract function
router.get('/api/emailtemplates/data/:subject', async (req, res) => {
try {
const templates = await Email_templates.find({ subject: req.params.subject });
const val = templates[0].template_file_link;
console.log(val);
textract.fromFileWithPath(val, (error, text) => {
console.log('This dox data', text);
return res.json({ text });
});
} catch (error) {
console.log(error);
}
});