【问题标题】:fs.readFile().toString terminated by empty stringfs.readFile().toString 由空字符串终止
【发布时间】:2013-09-24 15:36:22
【问题描述】:

以下节点脚本,(wc.js)返回一个不同于 Unix 实用程序 wc 的值;

fs = require('fs');
//console.log(fs.readFileSync(process.argv[2]).toString().split('\n') );
console.log(fs.readFileSync(process.argv[2]).toString().split('\n').length );

自身的输出是:

vagrant@precise32:~/stuff$ wc -l wc.js
3 wc.js
vagrant@precise32:~/stuff$ node wc.js wc.js
4

通过打印数组,文件似乎被一个额外的空字符串终止:

vagrant@precise32:~/stuff$ node wc.js wc.js
[ 'fs = require(\'fs\');',
'console.log(fs.readFileSync(process.argv[2]).toString().split(\'\\n\') );',
'//console.log(fs.readFileSync(process.argv[2]).toString().split(\'\\n\').length );',
'' ]

这是预期的行为吗?我在节点文档中看不到它的报告。

【问题讨论】:

    标签: node.js buffer tostring string-length


    【解决方案1】:

    您确定文件末尾没有尾随换行符吗?

    $ node wc.js wc.js
    [ 'fs = require(\'fs\');',
      'console.log(fs.readFileSync(process.argv[2]).toString().split(\'\\n\') );',
      '// console.log(fs.readFileSync(process.argv[2]).toString().split(\'\\n\').length );' ]
    

    你可以用.replace(/\n$/, '')忽略最后一个换行符,我相信这是wc的行为。

    【讨论】:

    • 在执行 buffer.toString 时会添加换行符:实际上即使是空文件也有额外的行。 vagrant@precise32:~/stuff$ touch tmpfile vagrant@precise32:~/stuff$ node wc.js tmpfile 1 vagrant@precise32:~/stuff$ wc -l tmpfile 0 tmpfile
    • 我很确定buffer.toString() 没有添加任何换行符。空字符串返回一行的原因是因为如果.split() 没有找到任何匹配的分割位置,它将返回一个包含原始字符串的单个元素的数组,即长度为1。fs.writeFileSync('tmp', ''); fs.readFileSync('tmp') //<Buffer > fs.writeFileSync('tmp', '\n'); fs.readFileSync('tmp') //<Buffer 0a>
    • > 所以,事实证明,根据 POSIX,每个文本文件(包括 Ruby 和 JavaScript 源文件)都应该以 \n thoughtbot.com/blog/no-newline-at-end-of-file 结尾(第一个鸭鸭结果)
    猜你喜欢
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多