[英]How do I read an CSV file in an EC2 instance folder as oppose to an S3 bucket in AWS?
我用 fast-csv 編寫了一個腳本,它可以在 amazon s3 中讀取 excel 文件,然后獲取數據並將其存儲在 mySQL 中。 我現在有一個 ec2 實例集並創建了一個名為“upload”的文件夾,並在其中存放了 CSV 文件。 我的問題是如何讀取 ec2 實例中的文件而不是 s3 存儲桶? 下面是當前使用的腳本
const s3Stream = s3.getObject(params).createReadStream()
stream = require('fast-csv').parseStream(s3Stream, {
headers: true, skip_blanks: true
})
.on("data", data => {
dataArr.push(data);
})
stream = require('fast-csv').parseStream(s3Stream)
.on("data", data => {
dataArr2.push(data);
})
.on("end", () => {
let csvStream = csv
.parse({ ignoreEmpty: true })
.on('data', function (dataArr2) {
myData.push(dataArr2);
})
.on('end', function () {
dataArr2.shift();
console.log('dataArr2 ' + myData)
if (dataArr.length > 0) {
let columnsIn = dataArr[0];
for (let key in columnsIn) {
headerDatas.push(key)
}
for (let key in columnsIn) {
orginalHeaderDatas.push(key)
}
for (i = 0; i < headerDatas.length; i++) {
newData = headerDatas[i].split(' ').join('_');
correctHeaderFormat.push(newData)
}
// Assigns approriate Sql property to headers
let databaseId = headerDatas[0].split(' ').join('_');
let leaseDiscription = headerDatas[1].split(' ').join('_');
//Removes Headers that are not DEC propertys
headerDatas.shift();
headerDatas.shift();
let newdatabaseId = databaseId + ' int(25) NOT NULL'
let newleaseDiscription = leaseDiscription + ' varchar(255) NULL'
//adds property to the end of the remaining headers in array
for (i = 0; i < headerDatas.length; i++) {
newData = headerDatas[i].split(' ').join('_') + ' dec(25,2) NULL';
updatedData.push(newData)
}
//Adds headers that were removed from array and primary key to updated array
let key = 'PRIMARY KEY (Database_ID)'
headersWithProperties.push(updatedData)
headersWithProperties.unshift(newleaseDiscription)
headersWithProperties.unshift(newdatabaseId)
headersWithProperties.push(key)
} else {
console.log('No columns');
}
// open the connection
connection.connect((error) => {
if (error) {
console.error(error);
} else {
let createTable = 'CREATE TABLE `CD 1`' + '(' + headersWithProperties + ')'
let insertData = 'INSERT INTO `CD 1` ' + '(' + correctHeaderFormat + ') ' + 'VALUES ?'
//create table
connection.query(createTable, (error, response) => {
console.log("bottom" + connection.query)
console.log(error || response);
});
//insert data
connection.query(insertData, [dataArr2], (error, response) => {
console.log("bottom" + connection.query)
console.log(error || response);
});
}
});
});
stream.pipe(csvStream);
});
如果我正確理解您的問題,您正在嘗試讀取本地的 csv 文件(與您的 node.js 和 mysql 在同一位置)而不是從 S3 存儲桶。 不要使用 s3 變量來獲取 csv 文件,而應該在本地讀取它。
fs.createReadStream('/path/to/upload/data.csv')
然后您可以使用與以前類似的方法將其解析到 mysql 數據庫中。 它看起來像這樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.