I'm writing a program I need to query a database for values which are comprised of a url, and save them to an array. Then I need them to take the strings in that array and create and write files with the last characters of them after the last slash in the each of the names pulled from a result in the query.
The urls are like:
http://examplesite.com/wp-content/uploads/YYYY/MM/17818380_1556368674373219_6750790004844265472_n-1.jpg
http://examplesite.com/wp-content/uploads/YYYY/MM/17818380_1556368674373219_6750790004844265472_n.jpg
https://examplesite.com/wp-content/uploads/YYYY/MM/10643960_909727132375975_2074842458_n-44x55.jpg
http://examplesite.com/wp-content/uploads/YYYY/MM/10643960_909727132375975_2078842458_n-320x150.jpg
My starting code is:
const mysql = require('mysql');
const process = require('process');
const glob = require('glob');
const fs = require('fs');
function connectToDB() {
return new Promise((resolve,reject)=>{
try {
var connection = mysql.createConnection({
host:"10.1x.xxx.x",
user: "username",
password: "password",
database: "mydb"
});
} catch(e) {
reject(e);
}
if(!connection) {
reject(new Error("No Connection"));
}
connection.connect(function(err) {
if(err) reject(err);
console.log("inside db")
resolve(connection);
});
});
}
function getFilesToReplace(connection){
return new Promise( (resolve, reject) => {
var urls = [];
var query = "select fullURL from my_postmeta left outer join my_posts on (my_postmeta.post_id = my_posts.id) where my_postmeta.meta_key=\"_my_pichosting_url\" ";
connection.query(query, function(err, result, fields){
if(err) {
reject(err);
}
for (var i in result) {
urls.push(result[i].fullURL.toLowerCase());
}
resolve(urls);
});
});
}
However, when I get to the main function, which is below:
async function main(){
try{
var theSQLconnection = await connectToDB();
}
catch(e){
console.log('failed to connect');
return;
}
try{
var urlsfromdb = await getFilesToReplace(theSQLconnection);
}
catch(err){
console.log('more problems: ', e)
return;
}
theSQLconnection.end();
console.log(urlsfromdb.length);
try{
for(var i = 0; i < urlsfromdb.length; i++){
var filecontent = `${urlsfromdb[i]}`;
fs.writeFile(`../../wp-content/uploads/newfolder/`, filecontent, function(err){
if(err){
return console.log("error overwriting .jpg file: ", err)
}
})
}
}
catch(e){
console.log(`error: ${e}`)
}
}
I get an error, namely:
error overwriting .jpg file: { [Error: EISDIR: illegal operation on a directory, open '../../wp-content/uploads/newfolder/'] errno: -21, code: 'EISDIR', syscall: 'open', path: '../../wp-content/uploads/scriptdeletedir/' }
Why am I getting this error? I want in new folder, to be files like 10643960_909727132375975_2078842458_n-320x150.jpg
, etc.