【发布时间】:2022-01-23 02:51:11
【问题描述】:
我正在尝试使用 fs 方法将 txt 文件转换为 json,它会抛出错误 omething is wrong TypeError: data.split is not a function 此处实施错误
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
【问题讨论】:
-
那么什么是数据?
console.log(data) -
@epascarello 数据打印为缓冲区 [0] DATA
-
data..toString().split() -
现在改变了它的印刷最终>>>>>> undefined
标签: javascript node.js fs