xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

How to fix Node.js fs.readFileSync toString Error All In One

How to fix Node.js fs.readFileSync toString Error All In One

SyntaxError: Unexpected end of JSON input ❌

error

fs.writeFile & fs.readFileSync 匹配错误

image

  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);
      }
    }
  }

demos

Node.js fs


import url from 'node:url';
import fs from 'node:fs';
// import * as pfs from "node:fs/promises";
import path from 'node:path';
import { fileURLToPath } from 'url';

const __dirname = path.resolve();
const __filename = fileURLToPath(import.meta.url);

https://nodejs.org/api/fs.html

When file is a filename, asynchronously writes data to the file, replacing the file if it already exists.
data can be a string or a buffer.

import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';

const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

import { writeFile } from 'node:fs';

writeFile('message.txt', 'Hello Node.js', 'utf8', callback);

https://nodejs.org/api/fs.html#fswritefilefile-data-options-callback

The mode option only affects the newly created file. See fs.open() for more details.

https://nodejs.org/api/fs.html#fswritefilesyncfile-data-options

https://nodejs.org/api/url.html

refs

https://stackoverflow.com/questions/56690940/unexpected-end-of-json-input-while-parsing-json-file-read-asynchronously

https://www.cnblogs.com/xgqfrms/p/13983568.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
历史上的今天:
2022-09-12 2022 年中国双一流大学在职研究生报考指南 All In One
2022-09-12 VSCode .wasm viewer extension All In One
2022-09-12 Rust to WebAssembly using js console.log All In One
2021-09-12 Flutter Text widget All In One
2020-09-12 React 性能优化
2020-09-12 awesome youtube programming video tutorials
2020-09-12 TypeScript & as & Type Assertion All In One
点击右上角即可分享
微信分享提示