READ THE FILE TEXT LINE BY LINE IN EXPRESS JS OR NODE USING PUG.
-If you are using this type of syntax- fs.appendFileSync(`./user/detail.txt`,`${data}`);
It is throwing error -SyntaxError: Unexpected token A in JSON at position 8
JSON.parse()(ref to read file at below)
is used to convert a string containing JSON notation into a Javascript object.
Your code turns the object into a string (by calling .toString()
) in order to try to parse it as JSON text.
The default .toString()
returns "[object Object]"
, which is not valid JSON; hence the error.
Correct syntax
— -fs.appendFileSync(`./user/detail.txt`,data)
— -fs.writeFileSync(`./user/detail.txt`,data);
HERE IS THE READ FILE PROCESS
try {
// read contents of the file
const data = fs.readFileSync('./user/detail.txt', 'UTF-8')
// split the contents by new line
const lines = data.split(/\r?\n/)
var arr=[]
// print all lines
lines.forEach(line => {
const li=line.split(/,/)// it is split the
arr.push(`{"name":"${li[0]}","phone":"${li[1]}","email":"${li[2]}","age":"${li[3]}","city":"${li[4]}"}`);
})
const result = arr.map(info => JSON.parse(info));
console.log(arr);
res.render("contactdetails",{result:result})
} catch (err) {
console.error(err)
}
})
If you download the file
app.get(`/single`,(req,res)=>{
res.download(folderPath+'/detail.txt', function(err) {//locate the path of txt file
if(err) {
res.send("Error");
}
else{
res.send("Downloaded")
}
})
})
Pug file
table.table
thead
tr
th FULL NAME
th PHONE NUMBER
th EMAIL ADDRESS
th Age
th City
tbody
- for (var i = 0; i < result.length-1; ++i) {
tr
td #{result[i].name}
td #{result[i].phone}
td #{result[i].email}
td #{result[i].age}
td #{result[i].city}
- }