开发者

How to store two file handlers in nodejs?

开发者 https://www.devze.com 2023-03-17 15:37 出处:网络
I need to open one file, parse it, make http requests and save the data into another file. Can I do it without nes开发者_运维知识库ting all the code in one place? (It makes code less readable.)

I need to open one file, parse it, make http requests and save the data into another file. Can I do it without nes开发者_运维知识库ting all the code in one place? (It makes code less readable.)

I'd like to have something like this in the end. Is it ok to write to global scope?

on_write_file = function(err, write_file) {
    // parse the data from the opening file
};
on_read_file = function(err, read_file) {
    fs.open('end_file', 'w', on_write_file);
};

fs.open('start_file', 'r', on_read_file);

In a web server, instead, it will be dangerous to use globals, what should I do then?


Yes you can, use .bind to curry data into a function.

on_write_file = function(read_file, err, write_file) {
    // parse the data from the opening file
};
on_read_file = function(err, read_file) {
    fs.open('end_file', 'w', on_write_file.bind(null, read_file));
};

fs.open('start_file', 'r', on_read_file);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号