Skip to content

Commit

Permalink
feat: support dynamic data for server js file
Browse files Browse the repository at this point in the history
  • Loading branch information
sky committed Oct 23, 2019
1 parent 5961636 commit 9a93b07
Showing 1 changed file with 27 additions and 13 deletions.
40 changes: 27 additions & 13 deletions lib/tool.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,22 +116,36 @@ exports.httpServer = (cfg, callback) => {
} else {
body.value = fs.readFileSync(filepath);
}
return;
}
} else if (response.statusCode === 404 ) {
} else if (response.statusCode === 404 && !path.extname(filepath) ) {
// auto match file ext
if (filepath.indexOf('.') === -1) {
const extKeys = Object.keys(httpserver.config.contentType);
const ext = extKeys.find(ext => {
const file = `${filepath}.${ext}`;
return fs.existsSync(file);
});
if (ext) {
response.setHeader('Content-Type', httpserver.config.contentType[ext]);
response.statusCode = 200;
body.value = fs.readFileSync(`${filepath}.${ext}`);
return;
const extKeys = Object.keys(httpserver.config.contentType);
const ext = extKeys.find(ext => {
const file = `${filepath}.${ext}`;
return fs.existsSync(file);
});
if (ext) {
response.statusCode = 200;
const fileLocalPath = `${filepath}.${ext}`;
if (ext === 'js') {
response.setHeader('Content-Type', httpserver.config.contentType.json);
try {
if (require.cache[fileLocalPath]) {
delete require.cache[fileLocalPath];
}
const result = require(fileLocalPath);
if (typeof result === 'function') {
body.value = JSON.stringify(result(request, response));
} else {
body.value = JSON.stringify(result);
}
return;
} catch(e) {
console.warn('[node-tool-utils] http serve error', e);
}
}
response.setHeader('Content-Type', httpserver.config.contentType[ext]);
body.value = fs.readFileSync(fileLocalPath);
}
}
};
Expand Down

0 comments on commit 9a93b07

Please sign in to comment.