I am trying to convert txt file to json using fs methods it is throwing an error omething is wrong TypeError: data.split is not a function
what is implemented wrong here
index.js
try {
let data = await fs.readFileSync(path.join(filePath));
const obj = {
User: "",
User: Location: "",
Company Name: "",
Notes: " "
};
const content = [];
data.split("\n").map((line) => {
if (line.startsWith("User:")) {
obj.title = line.substring(6);
} else if (line.startsWith("Company Name:")) {
obj.title = line.substring(6);
} else if (line.startsWith("User Location:")) {
obj.tags = line.substring(4).split(",");
} else if (line.startsWith("Notes:")) {
obj.tags = line.substring(4).split(",");
} else {
content.push(line);
}
});
obj.content = content.join("\n");
const finalres = fs.writeFileSync("output.json", JSON.stringify(obj));
console.log("Final>>>>>>", finalres);
res.send(finalres);
} catch(e) {
console.log("something is wrong", e);
}
doc.txt
User: Account Admin
User Location: New York, NY
Company Name: WeightWatcher
Notes: Enabling growth through experimentation and analysis to
build a world-class onboarding experience
Building and managing monitoring, configuration, control
plane, and operational services to allow
CodePudding user response:
in
await fs.readFileSync(path.join(filePath));
readFileSync
does not return promise. fix it by deleting the await
. it is a Sync
method to it will wait until it finished.
also readFileSync
will return Buffer. you can convert the buffer to a string or add the option like this :
fs.readFileSync(path.join(filePath),{encoding:'utf8'});
also fix the object to a valid json notation:
const obj = {
User: "",
"User Location": "",
"Company Name": "",
Notes: ""
};