Advertisement
NikolayPaskulov

Untitled

Oct 27th, 2014
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. var http = require("http"),
  2. url = require("url"),
  3. path = require("path"),
  4. fs = require("fs"),
  5. port = process.argv[2] || 8888;
  6.  
  7. http.createServer(function (request, response) {
  8. var string = '';
  9.  
  10. request.on('data', function (data) {
  11. string += data;
  12. });
  13.  
  14. request.on('end', function () {
  15. var array = JSON.parse(string);
  16. if (array[0] == 'read') {
  17. getFile(array[1]);
  18. return;
  19. }
  20. if (array[0] == 'write') {
  21. uploadUpdateFile(array[1], array[2]);
  22. return;
  23. }
  24. });
  25.  
  26. function uploadUpdateFile(file, content) {
  27. var path = 'public/upload/' + file + '.json',
  28. stringifyContent = JSON.stringify(content);
  29.  
  30. fs.writeFile(path, stringifyContent, function (err) {
  31. if (err) {
  32. console.log(err);
  33. } else {
  34. console.log('File is saved!!!');
  35. }
  36. });
  37. }
  38.  
  39. function getFile(currentFile) {
  40. var uri = url.parse(request.url).pathname,
  41. filename = path.join(process.cwd(), uri);
  42.  
  43. path.exists(filename, function (exists) {
  44. if (!exists) {
  45. response.writeHead(404, { "Content-Type": "text/plain" });
  46. response.write("404 Not Found\n");
  47. response.end();
  48. return;
  49. }
  50. if (fs.statSync(filename).isDirectory()) filename += '/public/get/' + currentFile + '.json';
  51.  
  52. fs.readFile(filename, function (err, data) {
  53. if (err) {
  54. response.writeHead(500, { "Content-Type": "text/plain" });
  55. response.write(err + "\n");
  56. response.end();
  57. return;
  58. }
  59.  
  60. response.writeHead(200);
  61. response.write(data, "binary");
  62. response.end();
  63. });
  64. });
  65. }
  66.  
  67.  
  68. response.setHeader("Access-Control-Allow-Origin", "*");
  69. response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
  70. response.setHeader("Access-Control-Allow-Headers", "Content-Type");
  71. response.setHeader("Access-Control-Max-Age", "1800");//30 min
  72.  
  73.  
  74. }).listen(parseInt(port, 10));
  75.  
  76.  
  77. console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement