search

Home  >  Q&A  >  body text

node.js fs.stat读取的文件长度为0

谷歌找了一圈没找到答案,先贴代码:

const fs = require('fs')
fs.watch('./test.log', {}, (e) => {
  const stats = fs.statSync('./test.log') 
  console.log(stats.size)
})

当你不断往test.log文件添加文字,会先打出0再打出实际文件长度,如下所示

请问有谁知道是为什么么,求解释!!

补充一下:
运行代码后,我用编辑器打开test.log这个文件,手动的往里面写东西。这个会有影响么?

PHP中文网PHP中文网2821 days ago776

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-17 13:53:45

    Print the information when the change occurs and take a look
    See what operations the editor performs on the file. Accessing/modifying the file will trigger the file change event
    Node writes the file and then monitors the file. Nothing appears as you said The problem is as follows:

    var fs = require('fs');
    var util=require('util');
    
    fs.watch('./test.log', {}, function(e){
        var stats = fs.statSync('./test.log');
        console.log(util.inspect(stats));//打印发生变化时的信息
        console.log(stats.size)
    });
    
    var writeStream=fs.createWriteStream('./test.log', {
        flags: 'a+',
        defaultEncoding: 'utf8'
    });
    
    setInterval(function(){
        writeStream.write("a");
    },1000);

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:53:45

    I haven’t tried it, it’s probably because the file was occupied when you were adding text,

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:53:45

    Just ctrl+s will be executed twice

    reply
    0
  • Cancelreply