首页 \ 问答 \ NodeJS中有多个writeFile(Multiple writeFile in NodeJS)

NodeJS中有多个writeFile(Multiple writeFile in NodeJS)

我有一个任务是将部分数据写入单独的文件中:

        fs.writeFile('content/a.json', JSON.stringify(content.a, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('a.json was updated.');
            }
        });
        fs.writeFile('content/b.json', JSON.stringify(content.b, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('b.json was updated.');
            }
        });
        fs.writeFile('content/c.json', JSON.stringify(content.c, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('c.json was updated.');
            }
        });
        fs.writeFile('content/d.json', JSON.stringify(content.d, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('d.json was updated.');
            }
        });

但是现在我有4种不同的回调,所以当4个任务完成时我无法得到这个时刻。 是否可以并行执行4个writeFile调用并获取1个回调,这将在创建4个文件时调用?

PS

当然,我可以这样做:

fs.writeFile('a.json', data, function(err) {
  fs.writeFile('b.json', data, function(err) {
    ....
    callback();
  }
}

只是好奇有没有其他的方式来做到这一点。 谢谢。


I have a task to write parts of the data to separate files:

        fs.writeFile('content/a.json', JSON.stringify(content.a, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('a.json was updated.');
            }
        });
        fs.writeFile('content/b.json', JSON.stringify(content.b, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('b.json was updated.');
            }
        });
        fs.writeFile('content/c.json', JSON.stringify(content.c, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('c.json was updated.');
            }
        });
        fs.writeFile('content/d.json', JSON.stringify(content.d, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('d.json was updated.');
            }
        });

But now I have 4 different callbacks, so I can't get the moment, when all 4 task have been finished. Is it possible to parallel 4 writeFile calls and get only 1 callback, which will be called when 4 files was created?

P.S.

Of course I can do smth like:

fs.writeFile('a.json', data, function(err) {
  fs.writeFile('b.json', data, function(err) {
    ....
    callback();
  }
}

Just curious is there any other way to do this. Thanks.


原文:https://stackoverflow.com/questions/26413329
更新时间:2022-02-10 17:02

最满意答案

您确实可以将对象“转换”为特定类型。

object stringAsObject = "This is a string";
string stringAsString = (string)stringAsObject;

但在这种情况下,我建议使用泛型。 在某些情况下,创建泛型方法可能有点复杂 - 幸运的是我不相信这是其中之一。

使用泛型,您不必将所有内容更改为“对象”,编译器可以为您跟踪类型。 这将允许它显示您的代码中的许多错误。

为了给你一个起点,我尝试在这里将对象池类更改为通用实现。 我为我改变的事情和你仍然需要处理的事情添加了评论。 注意我没有运行它,只是检查了Visual Studio中没有突出显示的错误,因此一旦开始调试,可能仍需要更改一些内容。 :)

// Changed to Generics. This makes the class easier to use.
public class PoolOfObjects<T>
{
    // Changed to private - you do not want this accessible from the outside
    // Changed the type to T so you do not have to cast.
    private T[] _objects;

    // Changed to prefix with _. 
    // Not all coding guidelines do this, but whatever you do be consistent.
    // Changed to states as there appears to be on per object.
    private bool?[] _states;

    // Using the standard Func<T> (function returning T)
    // instead of introducing a new delegate type
    private Func<T> _creator;

    // Changed to camelCase and Func<T> instead of custom delegate
    public PoolOfObjects(int objectsCount, Func<T> creator)
    {
        // Changed to remember the creator
        _creator = creator;
        // I left this an array, but consider changing to List<T>,
        // then the list can grow as needed. 
        _objects = new T[objectsCount];
        _states = new bool?[objectsCount];

        // removed initialization of objects
        // as it appears you do it when calling EjectObject
    }

    //Must return an exemplar by state of object when called 
    public T EjectObject(bool? state)
    {
        // TODO:
        // You never assign any values to the _states array,
        // so it will always have the value null.
        // this means if your method is called with true or false,
        // it will FAIL!
        // I do not know what "states" is for so I can't suggest how to fix it.

        // If it is to track if an object is already in use I recommend getting
        // rid of it and change your _objects to be:
        //   private Queue<T> _objects
        // Then this method will check if there are any items in the _objects queue,
        // if there is dequeue one and return it. If not, create a new object
        // and return it.
        // You then need to create another method to put the items back in the queue
        // after use.

        int i;
        for (i = 0; i < _states.Length; i++)
            if (_states[i] == state)
            { //create object if null
                if (_objects[i] == null)
                    // Changed to call your creator instead of assigning it.
                    _objects[i] = _creator();
                break;
            }
        // TODO: Your program will crash with an unclear error here if no object
        // has a state matching the requested state.
        return _objects[i];
    }
}

You can indeed "Cast" your object to a specific type.

object stringAsObject = "This is a string";
string stringAsString = (string)stringAsObject;

But in this case I would recommend using Generics. Creating generic methods can be a bit complex in some cases - luckily I do not believe this is one of them.

With generics you do not have to change everything to an "object" and the compiler can keep track of the types for you. This will allow it to show a number of errors you have in your code.

To give you a starting point to work from, I have tried changing your object pool class into a generic implementation here. I added comments for things I changed and things you still need to work on. Notice I did not run this, just checked no error is highlighted in Visual Studio, so there might still be a few things you need to change once you start debugging. :)

// Changed to Generics. This makes the class easier to use.
public class PoolOfObjects<T>
{
    // Changed to private - you do not want this accessible from the outside
    // Changed the type to T so you do not have to cast.
    private T[] _objects;

    // Changed to prefix with _. 
    // Not all coding guidelines do this, but whatever you do be consistent.
    // Changed to states as there appears to be on per object.
    private bool?[] _states;

    // Using the standard Func<T> (function returning T)
    // instead of introducing a new delegate type
    private Func<T> _creator;

    // Changed to camelCase and Func<T> instead of custom delegate
    public PoolOfObjects(int objectsCount, Func<T> creator)
    {
        // Changed to remember the creator
        _creator = creator;
        // I left this an array, but consider changing to List<T>,
        // then the list can grow as needed. 
        _objects = new T[objectsCount];
        _states = new bool?[objectsCount];

        // removed initialization of objects
        // as it appears you do it when calling EjectObject
    }

    //Must return an exemplar by state of object when called 
    public T EjectObject(bool? state)
    {
        // TODO:
        // You never assign any values to the _states array,
        // so it will always have the value null.
        // this means if your method is called with true or false,
        // it will FAIL!
        // I do not know what "states" is for so I can't suggest how to fix it.

        // If it is to track if an object is already in use I recommend getting
        // rid of it and change your _objects to be:
        //   private Queue<T> _objects
        // Then this method will check if there are any items in the _objects queue,
        // if there is dequeue one and return it. If not, create a new object
        // and return it.
        // You then need to create another method to put the items back in the queue
        // after use.

        int i;
        for (i = 0; i < _states.Length; i++)
            if (_states[i] == state)
            { //create object if null
                if (_objects[i] == null)
                    // Changed to call your creator instead of assigning it.
                    _objects[i] = _creator();
                break;
            }
        // TODO: Your program will crash with an unclear error here if no object
        // has a state matching the requested state.
        return _objects[i];
    }
}

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)