简体   繁体   中英

How do I save a file to my nodejs server from web service call

My issue is this: I have made a call to someones web service. I get back the file name, extension and the "bytes". Bytes actually come in as an array and at position 0 "Bytes[0]" is the following string:

JVBERi0xLjYKJeLjz9MKMSAwIG9iago8PC9EZWNvZGVQYXJtczw8L0sgLTEvQ29sdW1ucyAyNTUwL1Jvd3MgMzMwMD4+L1R5cGUvWE9iamVjdC9CaXRzUGVyQ29tcG9uZW50IDEvU3VidHlwZS9JbWFnZS9XaWR0aCAyNTUwL0NvbG9yU3BhY2UvRGV2aWNlR3JheS9GaWx0ZXIvQ0NJVFRGYXhEZWNvZGUvTGVuZ3RoIDI4Mzc0L0hlaWdodCAzMzAwPj5zdHJlYW0K////////y2IZ+M8+zOPM/HzLhzkT1NAjCCoEY0CMJNAjCR4c8HigRhBAi1iZ0eGth61tHhraTFbraRaYgQ8zMFyGyGM8ZQZDI8MjMI8M6enp9W6enp+sadIMIIEYwy/ggU0wwgwjWzSBUmwWOt/rY63fraTVNu6C7R7pN6+v///20v6I70vdBaPjptK8HUQfX9/17D/TMet+l06T//0v3/S9v+r98V0nH///7Ff+Ed3/v16X9XX/S/KP0vSb//W88ksdW18lzBEJVpPXT0k9b71///...

The string example above has been cut off for readability. How do I take that string and save it as a readable file? This case it's a pdf.

let pdfBytes = '{String shown above in example}'

You can use the Node.js File System Module to save the received buffer.
Assuming the encoding of your data is base64:

const fs = require('fs');

let pdfBytes = 'JVBERi0xLjYKJeLjz9...'

let writeStream = fs.createWriteStream('filename.pdf');

writeStream.write(pdfBytes, 'base64');

writeStream.on('finish', () => {  
    console.log('saved');
});

writeStream.end(); 

I am using the fs file system here to create and save the file. I use a lot of try catch in case anything goes wrong. This example shows how you could pass the data to a function that could then create the file for you.

const util = require('util');
const fs = require('fs');

const fsOpen = util.promisify(fs.open);
const fsWriteFile = util.promisify(fs.writeFile);
const fsClose = util.promisify(fs.close);

function saveNewFile(path, data) {
  return new Promise((async (resolve, reject) => {
    let fileToCreate;

    // Open the file for writing
    try {
      fileToCreate = await fsOpen(path, 'wx');
    } catch (err) {
      reject('Could not create new file, it may already exist');
      return;
    }

    // Write the new data to the file
    try {
      await fsWriteFile(fileToCreate, data);
    } catch (err) {
      reject('Error writing to new file');
      return;
    }

    // Close the file
    try {
      await fsClose(fileToCreate);
    } catch (err) {
      reject('Error closing new file');
      return;
    }

    resolve('File created');
  }));
};

// Data we want to use to create the file.
let pdfBytes = 'JVBERi0xLjYKJeLj...'
saveNewFile('./filename.pdf', pdfBytes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM