How to fix Node.js fs.readFileSync toString Error All In One
SyntaxError: Unexpected end of JSON input ❌
error
fs.writeFile
&fs.readFileSync
匹配错误
async appendFile(group) {
console.log(`append`)
const file = path.join(__dirname + `/videos.json`);
const data = fs.readFileSync(file);
console.log(`❌ data`, data, data.toString())
// const obj = JSON.parse(data.toString());
const obj = JSON.parse(data);
const json = [
...obj,
group,
];
await fs.writeFile(file, JSON.stringify(json, null, 4), (err) => {
if(err) {
console.log(`err ❌`)
} else {
console.log(`OK ✅`)
}
});
}
async writeJSONFile() {
const file = path.join(__dirname + `/videos.json`);
for (const group of this.groups) {
// console.log(`group`, group)
// console.log(`file`, file)
if (!fs.existsSync(file)) {
// create
// console.log(`create`)
const json = [group];
// console.log(`json`, json)
await fs.writeFile(file, JSON.stringify(json, null, 4), (err) => {
if(err) {
console.log(`err ❌`)
} else {
console.log(`OK ✅`)
}
});
} else {
// append
await this.appendFile(file, group);
}
}
}
solution
readFileSync
&writeFileSync
同步方式读写,文件
async appendFile(group) {
console.log(`append`)
const file = path.join(__dirname + `/videos.json`);
const data = fs.readFileSync(file);
console.log(`❌ data`, data, data.toString())
// const obj = JSON.parse(data.toString());
const obj = JSON.parse(data);
const json = [
...obj,
group,
];
fs.writeFileSync(file, JSON.stringify(json, null, 4), (err) => {
if(err) {
console.log(`err ❌`)
} else {
console.log(`OK ✅`)
}
});
}
async writeJSONFile() {
const file = path.join(__dirname + `/videos.json`);
for (const group of this.groups) {
// console.log(`group`, group)
// console.log(`file`, file)
if (!fs.existsSync(file)) {
// create
// console.log(`create`)
const json = [group];
// console.log(`json`, json)
fs.writeFileSync(file, JSON.stringify(json, null, 4), (err) => {
if(err) {
console.log(`err ❌`)
} else {
console.log(`OK ✅`)
}
});
} else {
// append
await this.appendFile(file, group);
}
}
}