Javascript &引用;SyntaxError:JSON中位置0处的意外标记u;错误

Javascript &引用;SyntaxError:JSON中位置0处的意外标记u;错误,javascript,node.js,express,Javascript,Node.js,Express,我有一个错误:“SyntaxError:JSON中位置0处的意外标记u”。但试了之后还是没有解决 const fs = require('fs') const path = require('path') module.exports = class Product { constructor(title) { this.title = title } saveProductData() { const filePath = path.

我有一个错误:“SyntaxError:JSON中位置0处的意外标记u”。但试了之后还是没有解决

const fs = require('fs')
const path = require('path')

module.exports = class Product {
    constructor(title) {
        this.title = title
    }

    saveProductData() {
        const filePath = path.join(path.dirname(process.mainModule.filename), 
        'data', 'products.json')
        fs.readFile(filePath, (err, fileContent) => {
            let products = []
            if (!err) {
                products = JSON.parse(fileContent)
            }
            products.push(this)
            fs.writeFile(filePath, JSON.stringify(products), (err) => {
                console.log(err)
            })
        })
    }

    static fetchAllProducts(cb) {
        const filePath = path.join(path.dirname(process.mainModule.filename), 
        'data', 'products.json')
        fs.readFile(filePath, (err, fileContent) => {
            if (err) {
                cb([])
            }
            cb(JSON.parse(fileContent))
        })
    }
}
我需要在product.json文件中写入一些数据。

Puting
cb(JSON.parse(fileContent))
else{}

将解决您的问题

您的
产品。json
无效或加载不正确。你能给我们看看你的json文件吗?看看你有什么<代码>控制台.log(文件内容);products=JSON.parse(fileContent)
fetchAllProducts
正在尝试调用
JSON.parse
,即使设置了错误。调用回调不会立即退出当前函数。在这种情况下,fileContent很可能是未定义的,未定义通过JSON.parse的隐式到字符串转换转换为“未定义”;“undefined”是以“u”开头的无效JSON。@MasoodSadri是
fileContent
undefined
,而不是
JSON。parse
@Bergi我明白了,但如何定义它呢?