UNPKG

1.45 kBJavaScriptView Raw
1const {
2 readFileSync,
3 lstatSync,
4 ensureFileSync,
5 writeFileSync
6} = require('fs-extra');
7const { relative } = require('path');
8const chalk = require('chalk');
9
10/**
11 * Get file content as utf-8 text.
12 * @param path {String} Absolute path to a text file.
13 */
14const getFileContent = function(path) {
15 return readFileSync(path, 'utf-8');
16};
17
18/**
19 * Judge a path is a directory.
20 * @param path {String} Absolute path to a file or directory.
21 * @return {Boolean}
22 */
23const isDirectory = function(path) {
24 return lstatSync(path).isDirectory();
25};
26
27/**
28 * Write file and ensure folder exists.
29 * @param path {String} File path.
30 * @param content {String} File content.
31 * @param rootPath {String} project path.
32 * @private
33 */
34const writeFile = function(path, content, rootPath) {
35 ensureFileSync(path);
36 console.log(chalk.green('Write'), relative(rootPath, path));
37 writeFileSync(path, content, 'utf-8');
38};
39
40/**
41 * Get directory path under root
42 * @param {string} dirname e.g. src/constant/test
43 * @param {string} root e.g. src
44 * @returns {string} e.g. constant/test
45 */
46const getCurrentDirectoryPath = function(dirname, root = 'src') {
47 const rootPosition = dirname.indexOf(root);
48 if (rootPosition === -1) {
49 throw new Error(`Current directory ${dirname} is not under ${root}`);
50 }
51 return dirname.slice(rootPosition + root.length);
52};
53
54module.exports = {
55 isDirectory,
56 getFileContent,
57 writeFile,
58 getCurrentDirectoryPath
59};