我想用MEAN堆栈来构建一个模拟plunker的简单操场:左侧有一个文件和一个textarea列表,右侧有一个实时预览。请注意,文件保存在临时文件夹中,实时预览是由该临时文件夹中的文件注入的iframe
。对服务器中文件的连续写入很慢
我有编码的东西。在前端,控制器监视textarea中文件的修改;每次发生变化时,render
将被调用,它将发送一个$http.post
来保存所有文件的新版本。
app.controller('Ctrl', ['$scope', 'codeService', function ($scope, codeService) {
...
$scope.$watch('files', function() {
codeService.render($scope.files)
}, true);
}]);
app.service('codeService', ['$http', function ($http) {
this.render = function (files) {
...
var arrayLength = files.length;
for (var i = 0; i < arrayLength; i++) {
$http.post('/writeFile', files[i]);
}
}
}
在后端:
router.post('/writeFile', function (req, res, next) {
console.log("router.post /writeFile");
var file = req.body;
var fs = require('fs');
fs.writeFileSync("public/tmp/" + file.name, file.body);
});
我的测试表明,对于第一修改中,这的确是写入到服务器上的文件。但是,对于连续修改,第二个和后续写入可能需要超过20秒EACH。
有没有人知道什么减慢了作品(第一个除外)?
此外,我应该拨打$http.post('/writeFile', files[i])
或以异步方式写router.post('/writeFile'...
?
编辑1:
我也想知道如果它是正确的写入通过以下方式HTTP请求(我在具有同步功能内的异步函数(即,HTTP POST)(即, ?render
)我应该让render
asynchonous):
app.service('codeService', ['$http', function ($http) {
this.render = function (files) {
...
var arrayLength = files.length;
for (var i = 0; i < arrayLength; i++) {
$http.post('/writeFile', files[i]);
}
}
}
当我看到在我的代码中的其他HTTP请求,时尚往往喜欢
o.create = function (post) {
return $http.post('/posts', post, {
headers: { Authorization: 'Bearer ' + auth.getToken() }
}).success(function (data) {
o.posts.push(data)
});
};
不使用'fs.writeFileSync',使用异步版本 – wong2
^这。 \ * Sync功能背后的全部理念是它们阻止*。 – estus
谢谢...请参阅我的更新... – SoftTimur