gpt4 book ai didi

node.js - learnyounode 'My First I/O' 示例

转载 作者:IT老高 更新时间:2023-10-28 23:26:25 25 4
gpt4 key购买 nike

这个程序让我很困惑。该程序的目标是计算文件中换行符的数量并在命令提示符下输出。 Learnyounode然后对文件运行他们自己的检查,看看他们的答案是否与您的答案相符。

所以我从答案开始:

var fs = require('fs');

var filename = process.argv[2];

file = fs.readFileSync(filename);

contents = file.toString();

console.log(contents.split('\n').length - 1);

learnyounode 验证该程序是否正确计算了新行数。但是当我将程序更改为以下任何一种时,它不会打印出与 learnyounode 打印出的数字相同的数字。

file = fs.readFileSync(C:/Nick/test.txt);
file = fs.readFileSync(test.txt);

难道nodejs readFileSync不能输入地址并正确读取吗?

最后,这个程序应该打印出程序中的换行符#。为什么每次我运行这个程序时,正确的程序和 learnyounode 都会打印出与换行数不同的相同数字?

例如,test.txt 中的换行数是 3。但是运行这个程序每次都会打印出不同的数字,比如 45、15、2 等。但同时,它被验证为正确的程序通过 learnyounode,因为他们的答案都匹配!怎么回事?

编辑:test.txt 是这样的

ok
testing
123

最佳答案

所以,我在本地机器上尝试了您的程序,您的程序运行良好。我不是learnyounode的专家。我只是在您提出问题后尝试过,但我想我了解它是如何工作的。因此,以下是您问题的答案:

Shouldn't nodejs readFileSync be able to input an address and read it correctly?

nodejs 的这个方法运行良好。您可以尝试打印文件的内容,您会发现没有问题。

Why does both the correct program and learnyounode print out the same number that is different from the amount of newlines everytime I run this program.

learnyounode 每次都使用不同的 filename 作为输入来运行您的程序。它通过针对同一文件运行自己的正确代码副本来验证程序的输出。

But when I change the program to any of the following, it doesn't print out the same number as learnyounode prints out.

这是因为此时,您的代码正在处理一个固定文件,而 learnyounode 在每次迭代时仍在处理不同的文件。

关于node.js - learnyounode 'My First I/O' 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20040993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com