-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
264 lines (240 loc) · 8.78 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#! /usr/bin/env node
// const tools = require('./tools.js');
const ora = require('ora');
const exec = require('await-exec')
const fs = require('fs').promises;
const version = require('./package.json').version;
const prompt = require('prompt-sync')({ sigint: true });
var projectName = process.argv[2];
var inputArgs = [];
var newPort = 3000;
var errorMsg = '';
var isExpress = true;
var isMongo = false;
var isMysql = false;
var isCors = false;
var isGit = false;
const expressImport = "const express = require('express');\n"
const mongoImport = "const MongoClient = require('mongodb').MongoClient;\n"
const mysqlImport = "const mysql = require('mysql');\n"
const corsImport = "const cors = require('cors');\n"
process.argv.forEach((val, index) => {
if (index > 2) {
inputArgs.push(val)
}
})
isProjectNameValid = (projectName) => {
if (projectName === '-h' || projectName === '--help') {
showHelp()
return false;
} else if (projectName === '-v' || projectName === '--version') {
console.log(`Version: ${version} \n`)
return false;
} else if (projectName === '' || projectName === null || projectName === undefined) {
errorMsg = "Project name cannot be empty! \nUse --help to get examples\n";
console.log(errorMsg)
return false
} else if (projectName.startsWith('-') || projectName.startsWith('_')) {
errorMsg = "Project name cannot start with a symbol \n"
console.log(errorMsg)
return false
} else if (!projectName.match("^[a-zA-Z0-9\-\_]*$")) {
errorMsg = "Project name can contain only a-z, A-Z, 0-9 \n"
console.log(errorMsg)
return false
} else {
return true
}
}
isArgsValid = (inputArgs) => {
var pass;
const validArgs = ['-p', '--port', '--git', '--mongodb', '--mysql', '--cors'];
if (inputArgs.every((val) => validArgs.includes(val))) {
pass = true
} else {
console.log('Unknown argument detected!\nConsider using --help\n')
pass = false
}
if (pass) {
if (inputArgs.includes('-p') || inputArgs.includes('--port')) {
let isPortNumberCorrect = false
while (!isPortNumberCorrect) {
let portNo = prompt('Enter port number: ');
if (portNo < 1024 || portNo > 9999) {
console.log('\nPort Number must be between 1024 and 9999')
pass = false
} else if (isNaN(portNo)) {
console.log('\nPlease enter correct integer')
pass = false
} else {
pass = true
newPort = Number(portNo)
isPortNumberCorrect = true
}
}
}
if (inputArgs.includes('--git')) {
isGit = true;
}
if (inputArgs.includes('--mongodb')) {
isMongo = true;
}
if (inputArgs.includes('--mysql')) {
isMysql = true;
}
if (inputArgs.includes('--cors')){
isCors = true
}
}
return pass
}
createBackendFolder = async (projectName) => {
const createBackendFolderLoader = ora({
text: 'Creating folder ' + projectName
});
try {
createBackendFolderLoader.start();
await fs.mkdir('./' + projectName + '/', (err) => {
if (err) throw err;
});
var indexJS = `${isExpress ? expressImport : ''}${isMongo ? mongoImport : ''}${isMysql ? mysqlImport : ''}
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(${newPort}, function () {
console.log('Server is running: ${newPort}');
});`
await fs.writeFile('./' + projectName + '/index.js', indexJS, (err) => {
if (err) throw err;
})
.then(createBackendFolderLoader.text = 'Created folder: ' + projectName)
.then(createBackendFolderLoader.succeed())
} catch (error) {
createBackendFolderLoader.text = 'Error creating folder: ' + projectName + '\n'
createBackendFolderLoader.fail()
process.exit(1)
}
}
initialiseExpress = async (projectName) => {
const initialiseExpressLoader = ora({
text: 'Installing Express '
});
try {
initialiseExpressLoader.start()
await exec('cd ' + projectName + '/ && npm init -y && npm install express', (err) => {
if (err) throw err;
})
.then(() => { initialiseExpressLoader.text = 'Installed Express' })
.then(() => { initialiseExpressLoader.succeed() })
} catch (error) {
initialiseExpressLoader.text = 'Error installing Express'
initialiseExpressLoader.fail()
process.exit(1)
}
}
initialiseGit = async (projectName) => {
const initialiseGitLoader = ora({
text: 'Initializing as a Git repository'
});
try {
initialiseGitLoader.start()
await exec('cd ' + projectName + '/ && git init', (err) => {
if (err) throw err;
})
var ignoreGit = `node_modules/
package-lock.json
`
await fs.writeFile('./' + projectName + '/.gitignore', ignoreGit, (err) => {
if (err) throw err;
})
.then(() => initialiseGitLoader.text = 'initialised as Git repository')
.then(() => initialiseGitLoader.succeed())
} catch (error) {
initialiseGitLoader.text = 'Error initializing as git repository'
initialiseGitLoader.fail()
process.exit(1)
}
}
initialiseMongo = async (projectName) => {
const initialiseMongoLoader = ora({
text: 'Installing Mongodb'
});
try {
initialiseMongoLoader.start()
await exec('cd ' + projectName + '/ && npm install mongodb', (err) => {
if (err) throw err;
})
.then(() => initialiseMongoLoader.text = 'Installed Mongodb')
.then(() => initialiseMongoLoader.succeed())
} catch (error) {
initialiseMongoLoader.text = 'Error installing Mongodb'
initialiseMongoLoader.fail()
process.exit(1)
}
}
initialiseMysql = async (projectName) => {
const initialiseMysqlLoader = ora({
text: 'Installing MySQL'
});
try {
initialiseMysqlLoader.start()
await exec('cd ' + projectName + '/ && npm install mysql', (err) => {
if (err) throw err;
})
.then(() => initialiseMysqlLoader.text = 'Installed MySQL')
.then(() => initialiseMysqlLoader.succeed())
} catch (error) {
initialiseMysqlLoader.text = 'Error installing MySQL'
initialiseMysqlLoader.fail()
process.exit(1)
}
}
initialiseCors = async (projectName) => {
const initialiseCORSLoader = ora({
text: 'Installing CORS'
});
try {
initialiseCORSLoader.start()
await exec('cd ' + projectName + '/ && npm install cors', (err) => {
if (err) throw err;
})
.then(() => initialiseCORSLoader.text = 'Installed CORS')
.then(() => initialiseCORSLoader.succeed())
} catch (error) {
initialiseCORSLoader.text = 'Error installing CORS'
initialiseCORSLoader.fail()
process.exit(1)
}
}
finalCheckLoader = (projectName) => {
const finalCheckLoader = ora({
text: 'Final checks'
});
finalCheckLoader.text = 'Your app is ready! \n\nRun the following command to serve your app live: \n > cd ' + projectName + ' && node index.js\n'
finalCheckLoader.succeed()
}
showHelp = () => {
console.log(`\nUsage: npx build-node-app [app-name] [arguments]\n\nExample: npx build-node-app hello-world\n`)
const helpTable = [
{ arg: '-p', argument: '--port', description: 'Specify port number to run app. Default port is 3000' },
{ arg: '', argument: '--mongodb', description: 'Install and import mongodb to your app' },
{ arg: '', argument: '--mysql', description: 'Install and import mysql to your app' },
{ arg: '', argument: '--cors', description: 'Install and import cors to your app' },
{ arg: '', argument: '--git', description: 'Initialise the project as git project. Add .git and .gitignore' },
{ arg: '-v', argument: '--version', description: 'Specify version of build-node-app' },
];
console.table(helpTable);
}
if (isProjectNameValid(projectName)) {
if (isArgsValid(inputArgs)) {
createBackendFolder(projectName)
.then(() => isExpress ? initialiseExpress(projectName) : null)
.then(() => isMongo ? initialiseMongo(projectName) : null)
.then(() => isMysql ? initialiseMysql(projectName) : null)
.then(() => isCors ? initialiseCors(projectName) : null)
.then(() => isGit ? initialiseGit(projectName) : null)
.then(() => finalCheckLoader(projectName))
}
}