61 lines
1.6 KiB
JavaScript
61 lines
1.6 KiB
JavaScript
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
|
||
} |