music-downloader/app/model/StoreModel.js

61 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

const fs = require('fs');
const request = require('request');
const _path = require("path");
//递归创建目录 同步方法
function mkdirsSync(dirname) {
//console.log(dirname);
if (fs.existsSync(dirname)) {
return true;
} else {
if (mkdirsSync(_path.dirname(dirname))) {
fs.mkdirSync(dirname);
return true;
}
}
}
function storeResource(path, url) {
path = handlePath(path);
return new Promise((resolve, reject) => {
mkdirsSync(_path.dirname(path));
const writeableStream = fs.createWriteStream(path);
request.get({ url: url, timeout: 20000 }).pipe(writeableStream).on('close', () => {
resolve(true);
});
});
}
async function storeMusic(path, url) {
return await storeResource(path, url);
}
function storeLrc(path, content) {
path = handlePath(path);
return new Promise((resolve, reject) => {
mkdirsSync(_path.dirname(path));
fs.writeFileSync(path, content, { overwrite: true });
resolve(true);
});
}
async function storePic(path, url) {
return await storeResource(path, url);
}
function checkMusicExists(path) {
return fs.existsSync(path);
}
function handlePath(path) {
// 必须保存到downloads目录过滤关键字符防止目录穿越
if(path.indexOf('/downloads/') != 0) path = '/downloads/' + path;
return path.replace('..', '').replace(/\.+/g, '.').replace(/\/+/g, '/').replace(/\\+/g, '\\');
}
module.exports = {
storeMusic,
storeLrc,
storePic,
checkMusicExists
}