js.readFileSync读取为空(JSON.parse err),同时查看从python修改的JSON文件

2024-05-02 13:07:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用node.js编写一个server.js文件, 它将每秒监视python修改的json文件

如果文件被修改,服务器将读取此json文件并将其打印出来。 它会起作用的。 但是JSON.parse:SyntaxError的错误:JSON输入的意外结束有时会发生

下面是我用python生成文件的代码

di = {"lon":str(0),"lat":str(0)}
iteration = 0
while True:
    time.sleep(5)
    lon = np.random.randint(-180, high=180)
    lat = np.random.randint(-90, high=90)
    di["lon"] = str(lon)
    di["lat"] = str(lat)
    with open('./generate.json', 'w') as f:
        json.dump(di, f, ensure_ascii=False)
    
    # with open(f'./{iteration}.json', 'w') as f:
    #    json.dump(di, f)
    print(f"Done. iteration: {iteration}, lon: {lon}, lat: {lat}")
    iteration += 1

myserver.js的监视功能

generate_file_path = './navigation/generate.json'

let fsWait = false;
fs.watch(generate_file_path, function(event, filename){
    if (filename && event==='change'){
      if (fsWait) return;
      fsWait = setTimeout(()=>{
        fsWait = false;
      }, 100);
      let rawdata = fs.readFileSync(generate_file_path, 'utf8');
      try{
        let g_file = JSON.parse(rawdata);
        console.log(g_file);
      }catch (e){
        console.log(e);
      }
    }
});

错误将是这样的。 enter image description here

enter image description here

我发现这可能是一个readfile问题。 我像这样更改了服务器代码

let fsWait = false;
fs.watch(generate_file_path, function(event, filename){
  if (filename && event==='change'){
    if (fsWait) return;
    fsWait = setTimeout(()=>{
      fsWait = false;
    }, 100);
    let rawdata = fs.readFileSync(generate_file_path, 'utf8');
    try{
      // let g_file = JSON.parse(rawdata);
      console.log(rawdata);
    }catch (e){
      console.log(e);
    }
  }
});

有时它什么也不打印。 enter image description here

右边是python生成日志,左边是server.js。 (迭代7、10、17缺少server.js读取的内容)

我尝试过修改python的睡眠时间,但是读取空文件的错误仍然存在。 由于fs.readFileSync有时工作,有时失败,我不知道如何调试这种问题


Tags: 文件pathjsonjsfsgeneratefilelon
1条回答
网友
1楼 · 发布于 2024-05-02 13:07:46

这表触发了多次。这就是为什么需要设置超时。只要将读数移到setTimeout中,就不会被其他事件捕获

let fsWait = false;
fs.watch(generate_file_path, function(event, filename){
  if (filename && event==='change'){
    if (fsWait) return;
    fsWait = setTimeout(()=>{
      fsWait = false;
      let rawdata = fs.readFileSync(generate_file_path, 'utf8');
      try{
        // let g_file = JSON.parse(rawdata);
        console.log(rawdata);
      }catch (e){
        console.log(e);
      }


    }, 100);
  }
});

相关问题 更多 >