根据Node.js中的缓冲区数据创建文件 [英] Create file based on buffer data in nodejs

查看:150
本文介绍了根据Node.js中的缓冲区数据创建文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am sending from front end client side a file, on the server side I have something like this:

{ 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] }

我需要创建的文件可能基于那里的缓冲区,我该怎么办?

What I need is to create the file may be based on that buffer that is there, how can I do it?

我已经搜索了很多,没有找到任何解决方案.

I already searched a lot and didn't find any solution.

这是我到目前为止尝试过的:

This is what I tried so far:

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!');
  });
});

推荐答案

您可以使用 Buffer 可用于NodeJS:

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方法中也可以指定

编码.

Encoding could also be specified in the overloaded from method.

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"

以可读格式提供数据之后,可以使用 fs NodeJS中的模块.

After you have data available in the readable format, you could store it using the fs module in NodeJS.

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

因此,将缓冲的输入转换为字符串后,需要将字符串传递给writeFile方法.您可以查看fs模块的文档.它将帮助您更好地了解事物.

So, after converting the buffered input to string, you need to pass the string into the writeFile method. You could check the documentation of the fs module. It will help you better understand things.

这篇关于根据Node.js中的缓冲区数据创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆