You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
2.5 KiB
96 lines
2.5 KiB
const path = require("path");
|
|
const fs = require("fs");
|
|
|
|
function listNotesInDirectory(directoryPath = "") {
|
|
return new Promise(function(resolve, reject) {
|
|
fs.readdir(directoryPath, function(err, files) {
|
|
if (err) return reject(err);
|
|
|
|
resolve(
|
|
files
|
|
.map(fPath => ({
|
|
ext: path.extname(fPath),
|
|
name: fPath,
|
|
title: path.basename(fPath, path.extname(fPath)),
|
|
path: path.join(directoryPath, fPath)
|
|
}))
|
|
.filter(
|
|
({ ext }) =>
|
|
ext === ".md" || ext === ".txt" || ext === ".utf8"
|
|
)
|
|
);
|
|
});
|
|
});
|
|
}
|
|
|
|
function getNoteTime(fullPath) {
|
|
return new Promise((a, r) => {
|
|
fs.stat(fullPath, (err, stats) => {
|
|
if (err) return r(err);
|
|
|
|
a({
|
|
lastModified: stats.mtime,
|
|
created: stats.ctime,
|
|
size: stats.size
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
function getNoteContent(fullPath) {
|
|
return new Promise((a, r) =>
|
|
fs.readFile(fullPath, "utf8", (err, data) => {
|
|
if (err) return r(err);
|
|
a({ content: data });
|
|
})
|
|
);
|
|
}
|
|
|
|
async function loadNotesInDirectory(directoryPath = "") {
|
|
const files = await listNotesInDirectory(directoryPath);
|
|
|
|
return await Promise.all(
|
|
files.map(async ({ path, title, ext }) => {
|
|
const [noteTime, noteContent] = await Promise.all([
|
|
getNoteTime(path),
|
|
getNoteContent(path)
|
|
]);
|
|
|
|
return {
|
|
path,
|
|
title,
|
|
...noteTime,
|
|
...noteContent
|
|
};
|
|
})
|
|
);
|
|
}
|
|
|
|
async function saveNoteInDirectory(
|
|
{ directory, defaultExtension },
|
|
{ title, content }
|
|
) {
|
|
let fullPath = path.join(directory, `${title}.${defaultExtension}`);
|
|
|
|
const match = (await listNotesInDirectory(directory)).filter(
|
|
f => f.title === title
|
|
);
|
|
|
|
if (match && match.length > 0) fullPath = match[0].path;
|
|
console.log("tryint to write note: ", fullPath, " - ", match);
|
|
|
|
return Promise.all([
|
|
new Promise((a, r) => {
|
|
fs.writeFile(fullPath, content, "utf8", err => {
|
|
if (err) return r(err);
|
|
a();
|
|
});
|
|
})
|
|
]);
|
|
}
|
|
|
|
module.exports = {
|
|
loadNotesInDirectory,
|
|
saveNoteInDirectory
|
|
};
|