如何读取EC2实例文件夹中的CSV文件,而不是AWS中的S3存储桶



我用fast csv编写了一个脚本,可以读取amazons3中的excel文件,然后获取数据并将其存储在mySQL中。我现在有了一个ec2实例集,并创建了一个名为"上传"的文件夹,并将CSV文件放在其中。我的问题是,如何读取ec2实例中的文件,而不是s3 bucket?以下是使用的当前脚本

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数据库中。它看起来像这个

最新更新