javascript - Node File System Create Directory and files on post route -
i have dashboard generates json data , saves .json file. written in php various reasons have re-written application in node. code below takes post data , should check see if file exists if update if not should create file , directory.
however seems create first file , cannot fathom why doesn't create subsequent files post route called once each post.
the post method looks this
$.ajax({ type : "post", url : '/save/', datatype : 'json', data : { category : settings.category_id, name : settings.campaignid, json : json.stringify(settings) } });
i have debugged , when called correct file paths passed if file isn't being written data.
during debugging using node-inspector , nodemon code loops through requested new file names , gives me error code enoent, should follow create file path.
if know node , file system module , feel helping me out amazing if it's pointing me in direction of more tutorials, ... great!
-
'use strict' const fs = require('fs'); const path = require('path'); const express = require('express'); const router = express.router(); /* save data */ router.post('/', function(req, res) { if (!(req.body.json && req.body.name && req.body.category)) { res.sendstatus(400); return; } let dir = 'public/saveddata/' + req.body.category; let filepath = dir + '/' + req.body.name + '.json'; fs.access(filepath, function(error) { console.log(filepath); console.log(error.code); if (error) { if (error.code == 'enoent') { console.log(error.code); //debugger; // create file since doesn't exist createfile(req, res, filepath); } else { //debugger; console.log('access error:', error); res.sendstatus(500); } } else { //debugger; // update file since exists updatefile(req, res, filepath); } }); }); function createfile(req, res, filepath) { try { let json = json.parse(req.body.json); let output = json.stringify([json], null, 4); fs.mkdir(path.dirname(filepath), function(error) { if (error) { if (error.code == 'eexist') { updatefile(req, res, filepath); } else { res.sendstatus(500); console.log('create file error :', error); } } else { fs.writefile(filepath, output, function(error) { if (error) { res.sendstatus(500); console.log('write file error :', error); } else { res.sendstatus(200); console.log('data saved'); } }); } }); } catch (error) { res.sendstatus(500); console.log(error); } } function updatefile(req, res, filepath) { try { fs.readfile(filepath, 'utf-8', function(error, data) { if (error) { res.sendstatus(500); console.log('update error:', error); } else { try { let newjson = json.parse(req.body.json); let jsonarray = json.parse(data); let output; jsonarray.push(newjson); output = json.stringify(jsonarray, null, 4); fs.writefile(filepath, output, function(error) { if (error) { res.sendstatus(500); console.log(error); } else { res.sendstatus(200); console.log('data saved'); } }); } catch (error) { res.sendstatus(500); console.log(error); } } }); } catch (error) { res.sendstatus(500); console.log(error); } } module.exports = router;
instead of checking if file exists, should try write flags wx
, creates file fails if exist. way won't subjecting race conditions. suggest package mkdirp
, not emit error if directory exists.
router.post('/', (req, res) => { if (!(req.body.json && req.body.name && req.body.category)) { res.sendstatus(400); return; } const dirpath = `public/saveddata/${req.body.category}`; const filepath = `${dirpath}/${req.body.name}.json`; mkdirp(dirpath, err => { if (err) { console.error('mkdirp failed', err); return res.sendstatus(500); } const output = json.stringify([json.parse(req.body.json)]); fs.writefile(filepath, output, { flags: 'wx' }, err => { if (err) { console.error('writefile failed', err); return res.sendstatus(500); } console.log('data saved'); res.sendstatus(200); }); ); });
make sure sanitize req.body.name
, req.body.category
parameters, since expose filesystem unintentional overwrites.
Comments
Post a Comment