【发布时间】:2016-09-30 16:07:51
【问题描述】:
我有一个 node.js(语法实际上是 Typescript)应用程序:
- 在某些 HTTP 请求处理程序中异步写入文件中的每日计数和
- 一个 cron 作业(在使用 node-cron 模块完成的节点应用程序内)在午夜重置该文件
非阻塞事件循环循环对我来说不是很清楚(it's not single thread 如果我做对了的话),我担心在我写信时 cron 模块正在重置文件的情况它。
我需要担心吗?就像在我承诺的fs.writeFile 正在写作时设置的全局标志一样?有没有更优雅的处理方式?
谢谢,如果这是一个愚蠢的问题,对不起。
这是我的代码框架:
import * as fs from 'fs';
import * as path from 'path';
import { CronJob } from 'cron';
import { pfs } from './promisifiedFs';
const daily_file = '/path_to_my_file'
new CronJob('0 0 * * * *', function() {
fs.writeFileSync(daily_file, 0, {'flag': 'w'});
}, null, true);
// somewhere called inside an HTTP GET handler
async function doBill(data) {
const something = //....
const currentCountRaw = await pfs.readfilePromisified(daily_file, 'utf-8');
const currentCount = parseFloat(currentCountRaw) || 0;
await pfs.writeFilePromisified(daily_file, currentCount + something, {'flag': 'w'});
}
【问题讨论】:
-
您能否更具体地说明“重置”文件的含义?使用带有
0和'a'标志的writeFileSync将在每次运行文件时将0附加到文件中,而带有'w'标志的writeFilePromisified将覆盖文件currentCount + something中的任何内容。这是故意的吗? -
@dvlsg 抱歉
a是错字 -
没问题,我认为是这样,但我不确定。所以这里的目标是你有一个从 0 开始的文件,随着时间的推移,这个数字会增加并被某个数字覆盖(因为我们不知道
something发生了什么)每次doBill被调用,直到下一个CronJob运行?
标签: node.js concurrency io file-writing