对服务器中文件的连续写入很慢
我想用MEAN模块构build一个简单的操作系统,模拟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); });
我的testing表明,对于第一次修改,它确实写入服务器中的文件。 但是,对于连续修改,第二个和后续写入可能需要超过20秒EACH。
有谁知道什么减慢了作品(除了第一个)?
此外,我应该调用$http.post('/writeFile', files[i])
或以asynchronous方式写router.post('/writeFile'...
?
编辑1:
我也想知道是否是正确的编写http请求以下面的方式(我有一个asynchronous函数(即http后)内同步function(即, render
)?我应该使render
asynchronous?):
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) }); };
你可以尝试重构你的代码,包括以下内容:
1)包裹你的观察者去抖动function。 https://lodash.com/docs/4.17.4#debounce
$scope.$watch('files', _.debounce(function () { codeService.render($scope.files) }, 1000), true);
它可以防止无用的电话
2)使用writeFile
而不是writeFileSync
fs.writeFile("public/tmp/" + file.name, file.body, (err) => { if (err) throw err; console.log('It\'s saved!'); });
NodeJs在asynchronous函数中的强大function,尽量避免代码中的同步调用。