简体   繁体   English

在 Node.js 中以 CWD 格式显示文件名和文件大小

[英]Display File Name and File Size in CWD in Node.js

I'm having trouble with this code.我在使用此代码时遇到问题。 What I'm trying to accomplish is getting a list of the file names and sizes to print on the same line in STDOUT.我想要完成的是获取要在 STDOUT 中的同一行上打印的文件名和大小的列表。 Currently, I am getting a list of file names, and then a list of sizes, but I want the sizes to display along side the names.目前,我得到一个文件名列表,然后是一个大小列表,但我希望大小与名称一起显示。 I am more familiar with how to do this in Python, and I'm surprised how hard this is to do in JavaScript.我更熟悉如何在 Python 中做到这一点,我很惊讶在 JavaScript 中做到这一点有多难。 So if you could not only help me correct my code, but help me understand how the code is working in JS, then it would be much appreciated.因此,如果您不仅可以帮助我更正我的代码,还可以帮助我了解代码在 JS 中的工作方式,那么我们将不胜感激。 Here is the code:这是代码:

const fs = require('fs');

let path = __dirname;

let files = fs.readdirSync(path);

for (var i = 0; i < files.length; i++){
  var fileStats = files[i];
  console.log("Start: " + fileStats);
  fs.stat(fileStats, function(err, stats){    
    console.log(stats.size);
  });
}

For comparison, this is what the code would look like in Python为了比较,这就是代码在 Python 中的样子

import os
import os.path

path = os.getcwd()
contents = os.listdir(path)

print(path)
for file in contents:
  size = os.path.getsize(file)
  print("File: {0}, Size: {1} Bytes".format(file, size))

Thanks谢谢

console.log() is always going to create a new line. console.log()总是会创建一个新行。 If you want it on the same line you have to do it in the same log.如果您希望它在同一行上,则必须在同一日志中进行。

const fs = require('fs');

let path = __dirname;

let files = fs.readdirSync(path);

for (var i = 0; i < files.length; i++){
  var fileStats = files[i];
  fs.stat(fileStats, function(err, stats){    
    console.log('Start:', fileStats, stats.size);
  });
}

You could use process.stdout.write() , which does not add the newline, but then your output would still be out of order.您可以使用process.stdout.write() ,它不会添加换行符,但是您的输出仍然会乱序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM