Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js how to read a file and then write the same file with two separate functions?

What I want to do is read a file and then be able to perform other operations with that information as I write the file. For example:

read file write file and at the same time perform MD5 hash, digital signing etc.

I could use fs.readfile and fs.writefile as one operation and just copy the file from the web server to my computer, but I don't think I could still do these same operations. Anyway, skipping the in between stuff. How do I use fs.readfile and writefile to create two separate functions to copy a file? Here is what I have been working on, and yes I've read these forums extensively in search of an answer.

var fs = require('fs');    function getData(srcPath) {  fs.readFile(srcPath, 'utf8', function (err, data) {         if (err) throw err;         return data;         }     ); }   function writeData(savPath, srcPath) {         fs.writeFile (savPath, (getData(srcPath)), function(err) {         if (err) throw err;             console.log('complete');         }     ); } //getData ('./test/test.txt'); writeData ('./test/test1.txt','./test/test.txt'); 

I want to be able to download files of any type and just make raw copies, with md5 hash etc attached to a JSON file. That will probably be a question for later though.

like image 893
Todd Keck Avatar asked Jul 15 '13 01:07

Todd Keck


People also ask

How do you read and write in the same file in node JS?

var fs = require('fs'); function getData(srcPath) { fs. readFile(srcPath, 'utf8', function (err, data) { if (err) throw err; return data; } ); } function writeData(savPath, srcPath) { fs. writeFile (savPath, (getData(srcPath)), function(err) { if (err) throw err; console.

How do you read from a file and write to another file in node JS?

fs. writeFileSync( 'writeMe. txt' , readMe); Asynchronous method to read and write from/into a file: To read/write the file in an asynchronous mode in fs module we use readFile() and writeFile() methods.

How do I read multiple text files in node JS?

One method to do this would be to nest the multiple readFiles and then have the writeFile nested inside. Something like this: var fs = require("fs"); fs. readFile('file1.


2 Answers

As suggested by dandavis in his comment, readFile does nothing because it is an asynchronous call. Check out this answer for additional information on what that means.

In short, an async call will never wait for the result to return. In your example, getData does not wait for readFile() to return the result you want, but will finish right away. Async calls are usually handled by passing callbacks, which is the last parameter to readFile and writeFile.

In any case, there are two ways to do this:

1.Do it asynchronously (which is the proper way):

function copyData(savPath, srcPath) {     fs.readFile(srcPath, 'utf8', function (err, data) {             if (err) throw err;             //Do your processing, MD5, send a satellite to the moon, etc.             fs.writeFile (savPath, data, function(err) {                 if (err) throw err;                 console.log('complete');             });         }); } 

2.Do it synchronously. Your code won't have to change much, you will just need to replace readFile and writeFile by readFileSync and writeFileSync respectively. Warning: using this method is not only against best practises, but defies the very purpose of using nodejs (unless of course you have a very legitimate reason).

Edit: As per OP's request, here is one possible way to separate the two methods, e.g., using callbacks:

function getFileContent(srcPath, callback) {      fs.readFile(srcPath, 'utf8', function (err, data) {         if (err) throw err;         callback(data);         }     ); }  function copyFileContent(savPath, srcPath) {      getFileContent(srcPath, function(data) {         fs.writeFile (savPath, data, function(err) {             if (err) throw err;             console.log('complete');         });     }); } 

This way, you are separating the read part (in getFileContent) from the copy part.

like image 78
verybadalloc Avatar answered Oct 09 '22 00:10

verybadalloc


I had to use this recently, so I converted verybadallocs answer to promises.

function readFile (srcPath) {   return new Promise(function (resolve, reject) {     fs.readFile(srcPath, 'utf8', function (err, data) {       if (err) {         reject(err)       } else {         resolve(data)       }     })   }) }  function writeFile (savPath, data) {   return new Promise(function (resolve, reject) {     fs.writeFile(savPath, data, function (err) {       if (err) {         reject(err)       } else {         resolve()       }     })   }) } 

Then using them is simple.

readFile('path').then(function (results) {   results += ' test manipulation'   return writeFile('path', results) }).then(function () {   //done writing file, can do other things }) 

Usage for async/await

const results = await readFile('path') results += ' test manipulation' await writeFile('path', results) // done writing file, can do other things 
like image 43
Trevor Avatar answered Oct 09 '22 01:10

Trevor