我正在使用nodejs和busboy接收json编码的文件。现在我想读取这个文件并在控制台上打印。
我想这应该很简单,但不知怎的,我不知道如何阅读和打印整个文件..
router.addRoute('/', function (req, res, params) {
if (req.method === 'POST') {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
// We are streaming! Handle chunks
file.on('data', function (data) {
//read file
});
// Completed streaming the file.
file.on('end', function () {
console.log('Finished with ' + fieldname);
});
});
// Listen for event when Busboy is finished parsing the form.
busboy.on('finish', function () {
res.statusCode = 200;
res.end();
});
req.pipe(busboy);
}
});
答案 0 :(得分:0)
in" file.on(' data')"回调你可以把文件的内容作为字符串。
router.addRoute('/', function (req, res, params) {
if (req.method === 'POST') {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
// We are streaming! Handle chunks
file.on('data', function (data) {
console.log(data);
});
// Completed streaming the file.
file.on('end', function () {
console.log('Finished with ' + fieldname);
});
});
// Listen for event when Busboy is finished parsing the form.
busboy.on('finish', function () {
res.statusCode = 200;
res.end();
});
req.pipe(busboy);
}
});
如果它是不完整的流数据。 file.on(' data')将每次触发部分文件内容,直到文件完成。如果你需要file.on(' end')回调和a全局变量。见下文,
router.addRoute('/', function (req, res, params) {
if (req.method === 'POST') {
var wholeData = '';
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
// We are streaming! Handle chunks
file.on('data', function (data) {
wholeData+=data;
});
// Completed streaming the file.
file.on('end', function () {
console.log('Finished with ' + fieldname);
console.log(wholeData);
});
});
// Listen for event when Busboy is finished parsing the form.
busboy.on('finish', function () {
res.statusCode = 200;
res.end();
});
req.pipe(busboy);
}
});