Skip to content
Navigation Menu
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Description
That’s pretty much the issue.
Works fine on OS X
Have googled and can’t find any way to increase Windows open file limit.
Is now also happening on OS X ‘ENFILE: file table overflow’
As far as I can tell this module always works down to an individual file level in async.
I’ve worked around this by changing the app structure (it will be the ~8000 files in node_modules) and doing a shell cp instead.
Is it something you need to look at handling via something like graceful-fs?
Добрый день.
Складывать в отдельный лог-файл сообщения об ошибках 404 — настолько обычное дело, что, казалось бы, и сложностей с этим быть не может. По крайней мере, так думал я, пока за одну секунду клиент не запросил полторы тысячи отсутствующих файлов.
Node.js-сервер выругался «EMFILE, too many open files» и отключился.
(В дебаг-режиме я специально не отлавливаю ошибки, попавшие в основной цикл)
Итак, что представляла собой ф-ия сохранения в файл:
log: function (filename, text) {
// запись в конец файла filename строки now() + text
var s = utils.digitime() + ' ' + text + '\n';
// utils.digitime() - возвращает текущую дату-время в виде строки в формате ДД.ММ.ГГГГ чч:мм:сс
fs.open(LOG_PATH + filename, "a", 0x1a4, function (error, file_handle) {
if (!error) {
fs.write(file_handle, s, null, 'utf8', function (err) {
if (err) {
console.log(ERR_UTILS_FILE_WRITE + filename + ' ' + err);
}
fs.close(file_handle, function () {
callback();
});
});
}
else {
console.log(ERR_UTILS_FILE_OPEN + filename + ' ' + error);
callback();
}
});
}
Ну то есть всё прямо «в лоб» — открываем, записываем, если какие ошибки — выводим на консоль. Однако, как говорилось выше, если вызывать её слишком часто, файлы просто не успевают закрываться. В линуксе, например, упираемся в значение kern.maxfiles со всеми неприятными вытекающими.
Самое интересное
Для решения я выбрал библиотеку async, без которой уже не представляю жизни.
Саму функцию log перенёс в «private» область видимости модуля, переименовав в __log и слегка модифицировав: теперь у неё появился коллбек:
__log = function (filename, text) {
return function (callback) {
var s = utils.digitime() + ' ' + text + '\n';
fs.open(LOG_PATH + filename, "a", 0x1a4, function (error, file_handle) {
if (!error) {
fs.write(file_handle, s, null, 'utf8', function (err) {
if (err) {
console.log(ERR_UTILS_FILE_WRITE + filename + ' ' + err);
}
fs.close(file_handle, function () {
callback();
});
});
}
else {
console.log(ERR_UTILS_FILE_OPEN + filename + ' ' + error);
callback();
}
});
};
};
Самое главное: в private создаём переменную __writeQueue:
__writeQueue = async.queue(function (task, callback) {
task(callback);
}, MAX_OPEN_FILES);
а в public-части модуля log выглядит теперь совсем просто:
log: function (filename, text) {
__writeQueue.push(__log(filename, text));
},
И всё?!
Именно. Другие модули по-прежнему вызывают эту ф-ию примерно как
function errorNotFound (req, res) {
utils.log(LOG_404, '' + req.method + '\t' + req.url + '\t(' + (accepts) + ')\t requested from ' + utils.getClientAddress(req));
..
и при этом никаких ошибок.
Механизм прост: задаём константе MAX_OPEN_FILES разумное число, меньшее чем максимально допустимое количество открытых файловых дескрипторов (например 256). Далее все попытки записи будут распараллеливаться, но только до тех пор, пока их количество не достигнет указанного предела. Все свежеприбывающие будут становиться в очередь и запускаться только после завершения предыдущих попыток (помните, мы добавляли callback? Как раз для этого!).
Надеюсь, данная статья поможет решить эту проблему тем, кто с ней столкнулся. Либо — что ещё лучше — послужит превентивной мерой.
Удачи.
Техническая поддержка Litebox Кассы
Page tree
Browse pages
- Jira links
Тип кассы: Windows 2.0
Версия кассы: 30.0.0
Ошибка: После запуска приложения отображается ошибка: Error: EMFILE: too many open files… (
Описание: Данная ошибка связана с битой базой данных кассового приложения.
Заявка в INTRA: 96525
Решение:
-
Удалить папку db-backup в %appdata%/Roaming/Litebox.
- No labels
Overview
Content Tools
- Powered by Atlassian Confluence 7.19.30
- Printed by Atlassian Confluence 7.19.30
- Report a bug
- Atlassian News
Atlassian
When I tried to run jest --watch
in a codebase, I received the following error:
Error: EMFILE: too many open files, watch
at FSEvent.FSWatcher._handle.onchange (fs.js:1372:28)
Emitted 'error' event at:
at NodeWatcher.checkedEmitError (/Users/seanmcp/dev/REPO/node_modules/sane/src/node_watcher.js:143:12)
at FSWatcher.emit (events.js:182:13)
at FSEvent.FSWatcher._handle.onchange (fs.js:1378:12)
A Google search of the error message produced three (!) results. The second was a PDF from Mozilla that recommended installing watchman
.
Why watchman
?
Permalink to “Why watchman?”
Watchman is a file-watching service from Facebook that will respond to changes in your files. Jest (also by Facebook) default to using watchman in --watch
mode.
Watchman is available on all major platforms. On a Mac or Linux with Homebrew installed, you can run:
brew install watchman
With that installed, Jest’s --watch
flag works as expected.
I hope that works for you (and saves you some valuable time)!
Happy testing!
I just moved my blog to hexo and ran into the “EMFILE: too many open files issue”. The hexo issue page recommends you run ulimit, but that doesn’t work on Windows.
After trying a ton of different things, I finally fixed it by upgrading to the latest version of Node.js v6.9.3.
Solution: Upgrade Node.js to at least v6.9.3
EMFILE: too many open files, open '[path]\node_modules\cheerio\index.js'
at Error (native)
at Object.fs.openSync (fs.js:634:18)
at Object.fs.readFileSync (fs.js:502:33)
at Object.Module._extensions..js (module.js:549:20)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.openGraphHelper ([path]\node_modules\hexo\lib\plugins\helper\open_graph.js:27:27)
at Object.wrapper [as open_graph] ([path]\node_modules\lodash\lodash.js:4994:19)
at eval (eval at <anonymous> ([path]\node_modules\ejs\lib\ejs.js:242:14), <anonymous>:49:189)
at eval (eval at <anonymous> ([path]\node_modules\ejs\lib\ejs.js:242:14), <anonymous>:55:1071)
at [path]\node_modules\ejs\lib\ejs.js:255:15
at _compiledSync ([path]\node_modules\hexo\lib\theme\view.js:122:20)
at View.renderSync ([path]\node_modules\hexo\lib\theme\view.js:50:21)
at Object.partial ([path]\node_modules\hexo\lib\plugins\helper\partial.js:42:17)
at Object.wrapper ([path]\node_modules\lodash\lodash.js:4994:19)
at eval (eval at <anonymous> ([path]\node_modules\ejs\lib\ejs.js:242:14), <anonymous>:30:35)
at eval (eval at <anonymous> ([path]\node_modules\ejs\lib\ejs.js:242:14), <anonymous>:30:2511)
at [path]\node_modules\ejs\lib\ejs.js:255:15
at _compiled ([path]\node_modules\hexo\lib\theme\view.js:127:30)