路径必须是字符串或缓冲区

时间:2018-06-28 04:27:20

标签: javascript node.js readfile

我现在正在从nodeschool.io学习NodeJS,第三个练习是关于I / O文件。

它要求我使用单个同步文件系统操作来编写程序,以读取文件并在控制台(stdout)中打印换行符数。要读取的文件的完整路径将作为第一个命令行参数(即process.argv [2])提供。

此练习的答案与我的答案相似,所以我真的知道我哪里做错了。这是我的解决方案:

var fs = require('fs');

var contents = fs.readFileSync(process.argv[2]);
var strs = contents.toString();
var lines = strs.split('/n').length - 1;

console.log(lines);

但是我得到一个错误:

TypeError: path must be a string or Buffer
    at Object.fs.openSync (fs.js:660:18)
    at Object.fs.readFileSync (fs.js:565:33)
    at Object.<anonymous> (D:\projects\dmt-node-study\first-io.js:3:19)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
    at Function.Module._load (internal/modules/cjs/loader.js:498:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:695:10)
    at startup (internal/bootstrap/node.js:201:19)

1 个答案:

答案 0 :(得分:0)

app.js

var fs = require('fs');
var contents = fs.readFileSync(process.argv[2]);
var strs = contents.toString();
var lines = strs.split('\n').length - 1;
console.log(lines);

从命令行运行代码

>node app test.txt

正在考虑的文本文件位于项目的根目录中。

相关问题