use of path.join everywhere

This commit is contained in:
Clément GOUIN
2019-06-20 10:40:48 +02:00
parent fe6cca6453
commit 07dd06a338
8 changed files with 77 additions and 76 deletions
+7 -12
View File
@@ -17,11 +17,6 @@ module.exports = (config) => {
const articles = []; const articles = [];
const log = (status, msg) => {
if (config['test'])
return;
console.log(status, msg);
};
const reload = (callback) => { const reload = (callback) => {
fw.fetchArticles((err, list) => { fw.fetchArticles((err, list) => {
@@ -31,9 +26,9 @@ module.exports = (config) => {
} }
articles.splice(0, articles.length, ...list); articles.splice(0, articles.length, ...list);
if (articles.length > 0) if (articles.length > 0)
log(cons.ok, `loaded ${articles.length} article${articles.length > 1 ? 's' : ''}`); console.log(cons.ok, `loaded ${articles.length} article${articles.length > 1 ? 's' : ''}`);
else else
log(cons.warn, `no articles loaded, check your configuration`); console.log(cons.warn, `no articles loaded, check your configuration`);
callback(true); callback(true);
}); });
}; };
@@ -42,16 +37,16 @@ module.exports = (config) => {
res.render(path, data, (err, html) => { res.render(path, data, (err, html) => {
if (err) { if (err) {
res.sendStatus(500); res.sendStatus(500);
log(cons.error, `failed to render ${path} : ${err}`); console.log(cons.error, `failed to render ${path} : ${err}`);
} else } else
res.status(code).send(html); res.status(code).send(html);
}); });
}; };
const showError = (path, code, res) => { const showError = (resPath, code, res) => {
const errorPath = `${config['data_dir']}/${config['home']['error']}`; const errorPath = path.join(config['data_dir'],config['home']['error']);
if (fs.existsSync(errorPath)) if (fs.existsSync(errorPath))
render(res, errorPath, {error: code, path: path}, code); render(res, errorPath, {error: code, path: resPath}, code);
else else
res.sendStatus(code); res.sendStatus(code);
}; };
@@ -79,7 +74,7 @@ module.exports = (config) => {
reload((res) => { reload((res) => {
if (res) if (res)
app.listen(config['node_port'], () => { app.listen(config['node_port'], () => {
log(cons.ok, `gitblog.md server listening on port ${config['node_port']}`); console.log(cons.ok, `gitblog.md server listening on port ${config['node_port']}`);
}); });
}); });
}; };
+1 -1
View File
@@ -15,7 +15,7 @@ const merge = (ref, src) => {
module.exports = () => { module.exports = () => {
try { try {
let configData = fs.readFileSync('./config.json', {encoding:'UTF-8'}); let configData = fs.readFileSync('config.json', {encoding:'UTF-8'});
let config = JSON.parse(configData); let config = JSON.parse(configData);
return merge(refConfig, config); return merge(refConfig, config);
} catch (error) { } catch (error) {
+13 -11
View File
@@ -1,15 +1,16 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path');
const getFileTree = (path, cb) => { const getFileTree = (dir, cb) => {
let list = []; let list = [];
let remaining = 0; let remaining = 0;
fs.readdir(path, {withFileTypes: true}, (err, items) => { fs.readdir(dir, {withFileTypes: true}, (err, items) => {
if (err) if (err)
return cb(err); return cb(err);
items.forEach((item) => { items.forEach((item) => {
if (item.isDirectory()) { if (item.isDirectory()) {
remaining++; remaining++;
getFileTree(`${path}/${item.name}`, (err, out) => { getFileTree(path.join(dir, item.name), (err, out) => {
if (err) if (err)
return cb(err); return cb(err);
list.push(...out); list.push(...out);
@@ -18,7 +19,7 @@ const getFileTree = (path, cb) => {
cb(null, list); cb(null, list);
}); });
} else { } else {
list.push(`${path}/${item.name}`); list.push(path.join(dir, item.name));
} }
}); });
if (remaining === 0) if (remaining === 0)
@@ -57,24 +58,25 @@ module.exports = (config) => {
.filter(path => path.indexOf(config['article']['index']) === path.length - config['article']['index'].length) .filter(path => path.indexOf(config['article']['index']) === path.length - config['article']['index'].length)
.map(path => path.substr(0, path.length - config['article']['index'].length)) .map(path => path.substr(0, path.length - config['article']['index'].length))
.map(path => path.match(/^\/(\d{4})\/(\d{2})\/(\d{2})\/$/)) .map(path => path.match(/^\/(\d{4})\/(\d{2})\/(\d{2})\/$/))
.filter(path => path && path.length > 1); .filter(matches => matches && matches.length > 1);
if (paths.length === 0) if (paths.length === 0)
cb(null, []); cb(null, []);
const list = []; const list = [];
let remaining = 0; let remaining = 0;
paths.forEach(path => { paths.forEach(matches => {
const article = { const article = {
path: config['data_dir'] + path[0] + config['article']['index'], path: path.join(config['data_dir'], matches[1], matches[2], matches[3], config['article']['index']),
year: parseInt(path[1]), parent: path.join(config['data_dir'], matches[1], matches[2], matches[3]),
month: parseInt(path[2]), year: parseInt(matches[1]),
day: parseInt(path[3]) month: parseInt(matches[2]),
day: parseInt(matches[3])
}; };
remaining++; remaining++;
readIndexFile(article.path, config['article']['thumbnail_tag'], (err, info) => { readIndexFile(article.path, config['article']['thumbnail_tag'], (err, info) => {
if (err) if (err)
return cb(err); return cb(err);
article.title = info.title || config['article']['default_title']; article.title = info.title || config['article']['default_title'];
article.thumbnail = info.thumbnail ? (config['data_dir'] + path[0] + info.thumbnail) : config['article']['default_thumbnail']; article.thumbnail = info.thumbnail ? path.join(article.parent, info.thumbnail) : config['article']['default_thumbnail'];
list.push(article); list.push(article);
remaining--; remaining--;
if (remaining === 0) if (remaining === 0)
+11 -10
View File
@@ -1,29 +1,30 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path');
const ncp = require('ncp').ncp; const ncp = require('ncp').ncp;
const copy = (src,dest) => { const copy = (src, dest) => {
ncp(src,dest, function(err){ ncp(src, dest, function (err) {
if(err) if (err)
console.error(err); console.error(err);
else else
console.log(`copied ${src} to ${dest}`); console.log(`copied ${src} to ${dest}`);
}); });
}; };
copy('./src/config.default.json','./config.example.json'); copy(path.join('src', 'config.default.json'), 'config.example.json');
if (!fs.existsSync('./data')) { if (!fs.existsSync('data')) {
fs.mkdirSync('./data'); fs.mkdirSync('data');
copy('./sample_data/home','./data'); copy(path.join('sample_data','home'), 'data');
const pad0 = n => ('0'+n).substr(-2); const pad0 = n => ('0' + n).substr(-2);
const datetime = new Date(); const datetime = new Date();
const dir = `./data/${datetime.getFullYear()}/${pad0(datetime.getMonth()+1)}/${pad0(datetime.getDate())}`; const dir = path.join('data', datetime.getFullYear().toString(), pad0(datetime.getMonth() + 1), pad0(datetime.getDate()));
if (!fs.existsSync(dir)) if (!fs.existsSync(dir))
fs.mkdirSync(dir, {recursive: true}); fs.mkdirSync(dir, {recursive: true});
copy('./sample_data/article',dir); copy(path.join('sample_data','article'), dir);
} }
+5 -4
View File
@@ -1,9 +1,10 @@
/* jshint -W117 */ /* jshint -W117 */
const request = require('supertest'); const request = require('supertest');
const fs = require('fs'); const fs = require('fs');
const path = require('path');
const utils = require('./test_utils'); const utils = require('./test_utils');
const dataDir = './test_data'; const dataDir = 'test_data';
const testIndex = 'testindex.ejs'; const testIndex = 'testindex.ejs';
const testError = 'testerror.ejs'; const testError = 'testerror.ejs';
@@ -38,7 +39,7 @@ describe('Test root path', () => {
}); });
}); });
test('404 no index but error page', done => { test('404 no index but error page', done => {
fs.writeFileSync(`${dataDir}/${testError}`, 'error <%= error %> at <%= path %>'); fs.writeFileSync(path.join(dataDir,testError), 'error <%= error %> at <%= path %>');
request(app).get('/').then(response => { request(app).get('/').then(response => {
expect(response.statusCode).toBe(404); expect(response.statusCode).toBe(404);
expect(response.text).toBe('error 404 at /'); expect(response.text).toBe('error 404 at /');
@@ -46,7 +47,7 @@ describe('Test root path', () => {
}); });
}); });
test('200 index page', done => { test('200 index page', done => {
fs.writeFileSync(`${dataDir}/${testIndex}`, 'hello there'); fs.writeFileSync(path.join(dataDir,testIndex), 'hello there');
request(app).get('/').then(response => { request(app).get('/').then(response => {
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(response.text).toBe('hello there'); expect(response.text).toBe('hello there');
@@ -64,7 +65,7 @@ describe('Test static files', () => {
}); });
}); });
test('404 invalid file but error page', done => { test('404 invalid file but error page', done => {
fs.writeFileSync(`${dataDir}/${testError}`, 'error <%= error %> at <%= path %>'); fs.writeFileSync(path.join(dataDir,testError), 'error <%= error %> at <%= path %>');
request(app).get('/somefile.txt').then(response => { request(app).get('/somefile.txt').then(response => {
expect(response.statusCode).toBe(404); expect(response.statusCode).toBe(404);
expect(response.text).toBe('error 404 at /somefile.txt'); expect(response.text).toBe('error 404 at /somefile.txt');
+2 -2
View File
@@ -1,8 +1,8 @@
/* jshint -W117 */ /* jshint -W117 */
const fs = require('fs'); const fs = require('fs');
const configFile = './config.json'; const configFile = 'config.json';
const tmpConfigFile = './config.temp.json'; const tmpConfigFile = 'config.temp.json';
beforeAll(() => { beforeAll(() => {
if (fs.existsSync(configFile)) { if (fs.existsSync(configFile)) {
+31 -30
View File
@@ -1,8 +1,9 @@
/* jshint -W117 */ /* jshint -W117 */
const fs = require('fs'); const fs = require('fs');
const path = require('path');
const utils = require('./test_utils'); const utils = require('./test_utils');
const dataDir = './test_data'; const dataDir = 'test_data';
const testIndex = 'testindex.md'; const testIndex = 'testindex.md';
const config = { const config = {
@@ -40,9 +41,9 @@ describe('Test function fileTree', () => {
}); });
test('empty folders', (done) => { test('empty folders', (done) => {
utils.createEmptyDirs([ utils.createEmptyDirs([
`${dataDir}/test/test`, path.join(dataDir, 'test', 'test'),
`${dataDir}/test/test2`, path.join(dataDir, 'test', 'test2'),
`${dataDir}/test2` path.join(dataDir, 'test2')
]); ]);
fw.fileTree(dataDir, (err, list) => { fw.fileTree(dataDir, (err, list) => {
expect(err).toBeNull(); expect(err).toBeNull();
@@ -53,8 +54,8 @@ describe('Test function fileTree', () => {
}); });
test('simple files', (done) => { test('simple files', (done) => {
const fileList = [ const fileList = [
`${dataDir}/f1.txt`, path.join(dataDir, 'f1.txt'),
`${dataDir}/f2.txt` path.join(dataDir, 'f2.txt')
]; ];
utils.createEmptyFiles(fileList); utils.createEmptyFiles(fileList);
fw.fileTree(dataDir, (err, list) => { fw.fileTree(dataDir, (err, list) => {
@@ -67,14 +68,14 @@ describe('Test function fileTree', () => {
}); });
test('nested files', (done) => { test('nested files', (done) => {
utils.createEmptyDirs([ utils.createEmptyDirs([
`${dataDir}/test/test`, path.join(dataDir, 'test', 'test'),
`${dataDir}/test2` path.join(dataDir, 'test2')
]); ]);
const fileList = [ const fileList = [
`${dataDir}/f1.txt`, path.join(dataDir, 'f1.txt'),
`${dataDir}/test/f2.txt`, path.join(dataDir, 'test', 'f2.txt'),
`${dataDir}/test/test/f3.txt`, path.join(dataDir, 'test', 'test', 'f3.txt'),
`${dataDir}/test2/f4.txt` path.join(dataDir, 'test2', 'f4.txt')
]; ];
utils.createEmptyFiles(fileList); utils.createEmptyFiles(fileList);
fw.fileTree(dataDir, (err, list) => { fw.fileTree(dataDir, (err, list) => {
@@ -95,7 +96,7 @@ describe('Test function fileTree', () => {
}); });
describe('Test index article reading', () => { describe('Test index article reading', () => {
const file = `${dataDir}/${testIndex}`; const file = path.join(dataDir, testIndex);
test('invalid file', (done) => { test('invalid file', (done) => {
fw.readIndexFile('invalid file', 'thumbnail', (err, info) => { fw.readIndexFile('invalid file', 'thumbnail', (err, info) => {
@@ -199,13 +200,13 @@ describe('Test article fetching', () => {
}); });
test('misplaced index file', (done) => { test('misplaced index file', (done) => {
utils.createEmptyDirs([ utils.createEmptyDirs([
`${dataDir}/test/test`, path.join(dataDir, 'test', 'test'),
`${dataDir}/2019/05/05`, path.join(dataDir, '2019', '05', '05')
]); ]);
utils.createEmptyFiles([ utils.createEmptyFiles([
`${dataDir}/${testIndex}`, path.join(dataDir, testIndex),
`${dataDir}/test/test/${testIndex}`, path.join(dataDir, 'test', 'test', testIndex),
`${dataDir}/2019/05/${testIndex}`, path.join(dataDir, '2019', '05', testIndex)
]); ]);
fw.fetchArticles((err, list) => { fw.fetchArticles((err, list) => {
expect(err).toBeNull(); expect(err).toBeNull();
@@ -215,10 +216,9 @@ describe('Test article fetching', () => {
}); });
}); });
test('empty index file', (done) => { test('empty index file', (done) => {
utils.createEmptyDirs([ const dir = path.join(dataDir, '2019', '05', '05');
`${dataDir}/2019/05/05`, const file = path.join(dir, testIndex);
]); utils.createEmptyDirs([dir]);
const file = `${dataDir}/2019/05/05/${testIndex}`;
utils.createEmptyFiles([file]); utils.createEmptyFiles([file]);
fw.fetchArticles((err, list) => { fw.fetchArticles((err, list) => {
expect(err).toBeNull(); expect(err).toBeNull();
@@ -226,20 +226,20 @@ describe('Test article fetching', () => {
expect(list.length).toBe(1); expect(list.length).toBe(1);
expect(list[0]).toEqual({ expect(list[0]).toEqual({
path: file, path: file,
parent:dir,
year: 2019, year: 2019,
month: 5, month: 5,
day: 5, day: 5,
title:'Untitled', title: 'Untitled',
thumbnail:'default.png' thumbnail: 'default.png'
}); });
done(); done();
}); });
}); });
test('correct index file', (done) => { test('correct index file', (done) => {
utils.createEmptyDirs([ const dir = path.join(dataDir, '2019', '05', '05');
`${dataDir}/2019/05/05`, const file = path.join(dir, testIndex);
]); utils.createEmptyDirs([dir]);
const file = `${dataDir}/2019/05/05/${testIndex}`;
fs.writeFileSync(file, ` fs.writeFileSync(file, `
# Title # Title
![thumbnail](./thumbnail.jpg) ![thumbnail](./thumbnail.jpg)
@@ -251,11 +251,12 @@ describe('Test article fetching', () => {
expect(list.length).toBe(1); expect(list.length).toBe(1);
expect(list[0]).toEqual({ expect(list[0]).toEqual({
path: file, path: file,
parent:dir,
year: 2019, year: 2019,
month: 5, month: 5,
day: 5, day: 5,
title:'Title', title: 'Title',
thumbnail:`${dataDir}/2019/05/05/./thumbnail.jpg` thumbnail: path.join(dataDir, '2019', '05', '05', './thumbnail.jpg')
}); });
done(); done();
}); });
+7 -6
View File
@@ -1,15 +1,16 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path');
const deleteFolderSync = (path) => { const deleteFolderSync = (dir) => {
if (!fs.existsSync(path)) if (!fs.existsSync(dir))
return; return;
fs.readdirSync(path, {withFileTypes: true}).forEach((item) => { fs.readdirSync(dir, {withFileTypes: true}).forEach((item) => {
if (item.isDirectory()) if (item.isDirectory())
deleteFolderSync(`${path}/${item.name}`); deleteFolderSync(path.join(dir,item.name));
else else
fs.unlinkSync(`${path}/${item.name}`); fs.unlinkSync(path.join(dir,item.name));
}); });
fs.rmdirSync(path); fs.rmdirSync(dir);
}; };
module.exports = { module.exports = {