[英]NodeJS Process Uploaded file with readline
I'm getting a file the client uploads which I receive with the following route: 我正在获取客户端通过以下途径上传的文件:
app.post('/upload', function(req, res){
var file = req.files.file;
//Process file inline
funcs.Process(file, req).then((data)=>{
//res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Disposition', 'attachment; filename=output.txt');
res.write(data, 'binary');
res.end();
}).catch((err)=>{
res.redirect('/?err='+err);
});
});
This is the code for funcs.Process
: 这是funcs.Process
的代码:
Process: function(file, req){
return new Promise(function(resolve, reject){
var lineReader = require('readline').createInterface({
input: fs.createReadStream(file)
});
var output = "";
lineReader.on('line', function (line) {
//some checks
ProcessLine(line).then((data)=>{
output += data + "\n";
}).catch((err)=>{
reject(`Invalid line in file [${line}].`);
});
});
lineReader.on('close', () => {
resolve(output);
});
});
However, I am getting the following error: 但是,我收到以下错误:
TypeError: path must be a string or Buffer, TypeError:路径必须是字符串或Buffer,
produced by the readline input: fs.createReadStream(file)
由readline input: fs.createReadStream(file)
产生input: fs.createReadStream(file)
As this is an uploaded file, how do I use it in the readline createInterface
? 由于这是一个上传的文件,如何在readline createInterface
使用它?
createReadStream accepts a string path. createReadStream接受字符串路径。
You're passing it req.files.file
, which is the file object created by express-fileupload
. 您正在传递给它req.files.file
,这是express-fileupload
创建的文件对象 。
You have two options: 您有两种选择:
Use the mv
function ( req.files.file.mv('<path>', callbackFunc)
) to first move the file to a known path on your server. 使用mv
函数( req.files.file.mv('<path>', callbackFunc)
)首先将文件移动到服务器上的已知路径。 Then pass this known path to fs.createReadStream
. 然后将此已知路径传递给fs.createReadStream
。
Create the read stream directly from the file data buffer exposed in req.files.file.data
using streamifier or similar library. 使用流化器或类似的库,直接从req.files.file.data
公开的文件数据缓冲区创建读取流。
var fileStream = require('streamifier').createReadStream(req.files.file.data)
This stream can then be passed to readline
as input directly. 然后可以将此流直接作为输入传递到readline
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.