小白開始學習前端全棧之node的文件操作的路徑問題

2015-08-23 22:00:00
hainuo
原創 1913
摘要:nodejs中操作對路徑有嚴格要求,否則將無法正確讀取文件,但是在facebook製作的server.js中有這樣的寫法
# 錶象> 根據代碼中所錶示,應該是以public爲根路徑,然後`comments.json`的路徑 **也在`public`目録下** 。`server.js`與`public`目録在衕一目録下# 問題> `get`時`comments.json`的路徑是在public下麵,但是`pos`t時,`comment.json`的路徑竟然與`public`目録衕一層級# 解決辦法> 在post的方法中統一增加public目録層級。# 修正後的代碼```nodejs/** * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */var fs = require('fs');var path = require('path');var express = require('express');var bodyParser = require('body-parser');var app = express();app.set('port', (process.env.PORT || 3000));app.use('/', express.static(path.join(__dirname, 'public')));app.use(bodyParser.json());app.use(bodyParser.urlencoded({extended: true}));app.get('/comments.json', function(req, res) { fs.readFile('comments.json', function(err, data) { res.setHeader('Cache-Control', 'no-cache'); res.json(JSON.parse(data)); });});app.post('/comments.json', function(req, res) { fs.readFile('public/comments.json', function(err, data) { var comments = JSON.parse(data); console.log(data); comments.push(req.body); console.log(comments) fs.writeFile('public/comments.json', JSON.stringify(comments, null, 4), function(err) { res.setHeader('Cache-Control', 'no-cache'); res.json(comments); }); });});app.listen(app.get('port'), function() { console.log('Server started: http://localhost:' + app.get('port') + '/');});```
發錶評論
叄 減 伍 =
評論通過審核後顯示。