问题
I am a Python developer, but the circumstances of a project I am working on now, oblige me to find a solution in Node.js.
I have check the documentation In the class File, I have this method: createReadStream, but who force me to download in local before read it.
However, the solution I search is just like to save the content in a variable so that I can read and interpret as I want.
This is the script of createReadStream() method:
var storage = require('@google-cloud/storage')();
var bucket = storage.bucket('my-bucket');
var fs = require('fs');
var remoteFile = bucket.file('image.png');
var localFilename = '/Users/stephen/Photos/image.png';
remoteFile.createReadStream()
.on('error', function(err) {})
.on('response', function(response) {
// Server connected and responded with the specified status
})
.on('end', function() {
// The file is fully downloaded.
})
.pipe(fs.createWriteStream(localFilename));
Thank's for your understanding and help.
回答1:
Script:
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket(bucket);
const remoteFile = bucket.file(file);
let buffer = '';
remoteFile.createReadStream()
.on('error', function(err) {console.log(err)})
.on('data', function(response) {
buffer += response
})
.on('end', function() {
//console.log(buffer);
res.send(buffer);
})
回答2:
Yes, it is possible, I did the following code for you, works perfectly in a cloud function:
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*/
'use strict';
const gcs = require('@google-cloud/storage')();
exports.readJSON = (req, res) => {
let file = gcs.bucket('YOUR_BUCKET').file('YOUR_FILE.JSON');
let readStream = file.createReadStream();
res.send(readStream);
};
and here you have the package.json (dependencies):
{
"name": "sample-http",
"version": "0.0.1",
"dependencies": {
"@google-cloud/storage": "1.6.0"
}
}
来源:https://stackoverflow.com/questions/53392131/is-there-a-way-to-directly-read-the-content-of-a-json-file-in-a-bucket-google-cl