Giter VIP home page Giter VIP logo

node-learn's People

Watchers

 avatar

node-learn's Issues

【fs 模块】writeFileSync 和 writeFile 的区别

同步 vs 异步

  • writeFileSync:同步方法,意味着它的线程会被阻塞,直到文件写入完成为止
  • writeFile:异步方法,意味着调用后程序可以继续执行其他任务而无需等待文件写入完成

返回值 vs 回调

  • writeFileSync:返回一个可能错误的对象,表示写入是否成功
  • writeFile:接受一个回调函数作为最后一个参数,写入完成后调用回调函数

适用场景

  • writeFileSync:简单的写入任务,不会对程序执行流程造成影响的情况下
  • writeFile:适用大多数情况,需要流程控制的应用程序

顺序

针对同一个文件的写入

  • 先writeFileSync后writeFile:writeFile 的 data 会覆盖writeFileSync 的 data
  • 先writeFile后writeFileSync:writeFile 的 data 会保留在文件中,若 writeFileSync 中 data 长度大于 writeFile 中 data 的长度,超过的部分会拼接在writeFile 的 data后面
fs.writeFile('base.txt', 'new', err => {
    if (!err) {
        console.log('data');
    }
});

fs.writeFileSync('base.txt', 'Hello world');

// base.txt
newlo world

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.