基于缓冲区数据创build文件

我从前端客户端发送一个文件,在服务器端我有这样的东西:

{ name: 'CV-FILIPECOSTA.pdf', data: <Buffer 25 50 44 46 2d 31 2e 35 0d 25 e2 e3 cf d3 0d 0a 31 20 30 20 6f 62 6a 0d 3c 3c 2f 4d 65 74 61 64 61 74 61 20 32 20 30 20 52 2f 4f 43 50 72 6f 70 65 72 ... >, encoding: '7bit', mimetype: 'application/pdf', mv: [Function: mv] } 

我需要的是创build文件也许基于那里的缓冲区,我怎么能做到这一点? 我已经search了很多,没有find任何解决scheme。

这是我迄今为止所尝试的:

 router.post('/upload', function(req, res, next) { if(!req.files) { return res.status(400).send("No Files were uploaded"); } var curriculum = req.files.curriculum; console.log(curriculum); curriculum.mv('../files/' + curriculum.name, function(err) { if (err){ return res.status(500).send(err); } res.send('File uploaded!'); }); }); 

你可以使用NodeJS提供的Buffer :

 let buf = Buffer.from('this is a test'); // buf equals <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74> let str = Buffer.from(buf).toString(); // Gives back "this is a test" 

编码也可以在重载from方法中指定。

 const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); // This tells that the first argument is encoded as a hexadecimal string let str = buf2.toString(); // Gives back the readable english string // which resolves to "this is a tést" 

以可读格式提供数据后,可以使用NodeJS中的fs模块进行存储。

 fs.writeFile('myFile.txt', "the contents of the file", (err) => { if(!err) console.log('Data written'); }); 

所以,在将缓冲的input转换为string后,您需要将该string传递给writeFile方法。 您可以检查fs模块的文档。 这将有助于你更好地理解事物。