Answers for "write file nodejs async"

0

writeFileSync

var fs = require('fs');

// Save the string "Hello world!" in a file called "hello.txt" in
// the directory "/tmp" using the default encoding (utf8).
// This operation will be completed in background and the callback
// will be called when it is either done or failed.
fs.writeFile('/tmp/hello.txt', 'Hello world!', function(err) {
  // If an error occurred, show it and return
  if(err) return console.error(err);
  // Successfully wrote to the file!
});

// Save binary data to a file called "binary.txt" in the current
// directory. Again, the operation will be completed in background.
var buffer = new Buffer([ 0x48, 0x65, 0x6c, 0x6c, 0x6f ]);
fs.writeFile('binary.txt', buffer, function(err) {
  // If an error occurred, show it and return
  if(err) return console.error(err);
  // Successfully wrote binary contents to the file!
});
Posted by: Guest on May-25-2020
0

async file read node js

function firstFunction(_callback) {
    // do some asynchronous work
    // and when the asynchronous stuff is complete
    const fs = require('fs');
    let jsonData;
    fs.readFile("industriesByCat.txt", 'utf8', function (err, data) {
        if (err) throw err;
        jsonData = JSON.parse(data);
        console.log(jsonData);
      	
      	//This is important for callback
        _callback();
    });

}

function secondFunction() {
    // call first function and pass in a callback function which
    // first function runs when it has completed
    firstFunction(function () {
        console.log('huzzah, I\'m done!');
    });
}
secondFunction();
Posted by: Guest on September-10-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language