?
Note.js,用stream读取文件的内容,注意decoder的用法
const fs = require(‘fs‘); ? var rr = fs.createReadStream(‘data\\foo.txt‘); ? // Pull off a header delimited by \n\n // use unshift() if we get too much // Call the callback with (error, header, stream) const StringDecoder = require(‘string_decoder‘).StringDecoder; function parseText(stream, callback) { stream.on(‘error‘, callback); stream.on(‘readable‘, onReadable); var decoder = new StringDecoder(‘utf8‘); var header = ‘‘; function onReadable() { var chunk; while (null !== (chunk = stream.read())) { var str = decoder.write(chunk); console.log(str); } } } ? parseText(rr, ????function(source, header, stream ) ????{ ????????console.write(header); ????} ? ); |
时间: 2024-11-06 12:39:23