function writeFile(fileName, data) {
return new Promise((resolve, reject) => {
fs.writeFile(fileName, data, (err) => {
if (err) reject(new Error(err));
resolve(); // <======
});
});
}
const http = require('http');
function getYandexDisk(url) {
return new Promise((resolve, reject) => {
http.get(url, (res) => {
if (res.statusCode !== 200) {
reject(new Error('Request Failed.\n' +
`Status Code: ${res.statusCode}`));
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => {
rawData += chunk;
});
res.on('end', () => {
let pattern = /href="(https:\/\/yadi.sk.+?)"/;
let arr = rawData.match(pattern);
(arr != null)
? resolve(arr[1])
: reject(new Error('Yandex disk url not found'));
});
});
});
}
(async () => {
try {
let yandexDisk = await getYandexDisk('http://site.com/');
console.log(yandexDisk);
} catch (err) {
console.error(err);
}
})();
async function getYandexDisk(url) {
return new Promise((resolve, reject) => {
http.get(url, (res) => {
if (res.statusCode !== 200) {
reject(new Error('Request Failed.\n' +
`Status Code: ${res.statusCode}`));
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => {
rawData += chunk;
});
res.on('end', () => {
let pattern = /href="(https:\/\/yadi.sk.+?)"/;
let arr = rawData.match(pattern);
if (arr != null) {
resolve(arr[1]);
} else {
reject(new Error('Yandex disk url not found'));
}
});
});
});
}
var xhr = new XMLHttpRequest();
var params = 'login=' + encodeURIComponent('login') +
'&password=' + encodeURIComponent('password');
xhr.open('GET', '/?' + params , false);
xhr.send();
if (xhr.status != 200) {
alert( xhr.status + ': ' + xhr.statusText );
} else {
console.log( xhr.responseText );
}