Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var http = require("http"),
- url = require("url"),
- path = require("path"),
- fs = require("fs"),
- port = process.argv[2] || 8888;
- http.createServer(function (request, response) {
- var string = '';
- request.on('data', function (data) {
- string += data;
- });
- request.on('end', function () {
- var array = JSON.parse(string);
- if (array[0] == 'read') {
- getFile(array[1]);
- return;
- }
- if (array[0] == 'write') {
- uploadUpdateFile(array[1], array[2]);
- return;
- }
- });
- function uploadUpdateFile(file, content) {
- var path = 'public/upload/' + file + '.json',
- stringifyContent = JSON.stringify(content);
- fs.writeFile(path, stringifyContent, function (err) {
- if (err) {
- console.log(err);
- } else {
- console.log('File is saved!!!');
- }
- });
- }
- function getFile(currentFile) {
- var uri = url.parse(request.url).pathname,
- filename = path.join(process.cwd(), uri);
- path.exists(filename, function (exists) {
- if (!exists) {
- response.writeHead(404, { "Content-Type": "text/plain" });
- response.write("404 Not Found\n");
- response.end();
- return;
- }
- if (fs.statSync(filename).isDirectory()) filename += '/public/get/' + currentFile + '.json';
- fs.readFile(filename, function (err, data) {
- if (err) {
- response.writeHead(500, { "Content-Type": "text/plain" });
- response.write(err + "\n");
- response.end();
- return;
- }
- response.writeHead(200);
- response.write(data, "binary");
- response.end();
- });
- });
- }
- response.setHeader("Access-Control-Allow-Origin", "*");
- response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
- response.setHeader("Access-Control-Allow-Headers", "Content-Type");
- response.setHeader("Access-Control-Max-Age", "1800");//30 min
- }).listen(parseInt(port, 10));
- 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