fan*_*ncy 107 javascript node.js
我需要在终端中传入一个文本文件,然后从中读取数据,我该怎么做?
node server.js file.txt
Run Code Online (Sandbox Code Playgroud)
如何从终端传递路径,如何在另一端读取?
mae*_*ics 156
您将要使用该process.argv数组访问命令行参数以获取文件名,并使用FileSystem模块(fs)来读取文件.例如:
// Make sure we got a filename on the command line.
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME');
process.exit(1);
}
// Read the file and print its contents.
var fs = require('fs')
, filename = process.argv[2];
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err;
console.log('OK: ' + filename);
console.log(data)
});
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,process.argv通常会有两个长度,第0个项是"节点"解释器,第一个是节点当前正在运行的脚本,之后的项目是在命令行上传递的.一旦从argv中提取了文件名,就可以使用文件系统函数来读取文件并对其内容执行任何操作.示例用法如下所示:
$ node ./cat.js file.txt
OK: file.txt
This is file.txt!
Run Code Online (Sandbox Code Playgroud)
[编辑]正如@wtfcoder所提到的,使用" fs.readFile()"方法可能不是最好的主意,因为它会在将文件产生回调函数之前缓冲文件的全部内容.这种缓冲可能会占用大量内存,但更重要的是,它没有利用node.js的一个核心功能 - 异步,事件I/O.
处理大文件(或任何文件,实际上)的"节点"方式是使用fs.read()和处理每个可用的块,因为它可从操作系统获得.但是,读取文件需要您自己(可能)增量解析/处理文件,并且可能不可避免地进行一些缓冲.
Gab*_*mas 24
fs.readFile()应该避免使用恕我直言,因为它将所有文件加载到内存中,并且在读取完所有文件之前它不会调用回调.
读取文本文件的最简单方法是逐行读取.我推荐一个BufferedReader:
new BufferedReader ("file", { encoding: "utf8" })
.on ("error", function (error){
console.log ("error: " + error);
})
.on ("line", function (line){
console.log ("line: " + line);
})
.on ("end", function (){
console.log ("EOF");
})
.read ();
Run Code Online (Sandbox Code Playgroud)
对于像.properties或json文件这样的复杂数据结构,您需要使用解析器(在内部它也应该使用缓冲读取器).
Ron*_*ite 20
将fs与节点对齐.
var fs = require('fs');
try {
var data = fs.readFileSync('file.txt', 'utf8');
console.log(data.toString());
} catch(e) {
console.log('Error:', e.stack);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 readstream 和 pipe 逐行读取文件,而无需一次将所有文件读入内存。
var fs = require('fs'),
es = require('event-stream'),
os = require('os');
var s = fs.createReadStream(path)
.pipe(es.split())
.pipe(es.mapSync(function(line) {
//pause the readstream
s.pause();
console.log("line:", line);
s.resume();
})
.on('error', function(err) {
console.log('Error:', err);
})
.on('end', function() {
console.log('Finish reading.');
})
);
Run Code Online (Sandbox Code Playgroud)
我正在发布一个完整的示例,我终于开始工作了。在这里,我正在rooms/rooms.txt从脚本中读取文件rooms/rooms.js
var fs = require('fs');
var path = require('path');
var readStream = fs.createReadStream(path.join(__dirname, '../rooms') + '/rooms.txt', 'utf8');
let data = ''
readStream.on('data', function(chunk) {
data += chunk;
}).on('end', function() {
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
170935 次 |
| 最近记录: |