我正在从我的存储桶中检索文件。
我收到该文件并想要阅读其内容,但我不想将其下载到我的本地项目
我只想读取内容,获取数据并用它进行其他操作。
我的代码:
export const fileManager = async () => {
try {
const source = 'upload/';
const options = { prefix: source, delimiter: '/' };
const remoteFile = st.bucket(bName).file('myData.csv');
const readFileData;
remoteFile
.createReadStream()
.on('error', err => {
console.log('error');
})
.on('response', response => {
readFileData = response;
console.log('success');
// Server connected and responded with the specified status and headers.
})
.on('end', () => {
console.log('end');
// The file is fully downloaded.
});
console.log("data", readFileData)
} catch (error) {
console.log('Error Is', error);
}
};
readFileData 未定义。
这可能吗?我找到的每个示例都涉及我下载文件。
createReadStream
是异步的并且立即返回。您必须使用回调来确定下载到内存何时完成。现在,您的代码总是会打印“数据未定义”,因为它试图在响应可用之前打印响应。
createReadStream
绝对是正确的方法,但你必须明白节点流如何工作 https://nodejs.org/api/stream.html以便正确处理结果。链接文档中有一个完整的部分阅读流 https://nodejs.org/api/stream.html#stream_readable_streams,这就是您想要在这里执行的操作。处理流的方式并非特定于 Cloud Storage - 对于所有节点流都是相同的。
以下有关读取节点流的问题的答案可能会对您有所帮助:
- Node.js:如何将流读入缓冲区? https://stackoverflow.com/questions/14269233/node-js-how-to-read-a-stream-into-a-buffer
- 将流转换为缓冲区? https://stackoverflow.com/questions/19906488/convert-stream-into-buffer
- 如何将 Node.js 流的内容读入字符串变量? https://stackoverflow.com/questions/10623798/how-do-i-read-the-contents-of-a-node-js-stream-into-a-string-variable
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)