node.js fs.stat读取的文件长度为0
PHP中文网
PHP中文网 2017-04-17 13:51:45
0
3
727

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

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中文网

认证0级讲师

reply all(3)
刘奇

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);
伊谢尔伦

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

刘奇

Just ctrl+s will be executed twice

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template