Node.js 如何读取一个文件,然后用两个单独的函数写入同一个文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17645478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js how to read a file and then write the same file with two separate functions?
提问by Todd Keck
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.
读文件写文件,同时执行MD5哈希,数字签名等。
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.
我可以使用 fs.readfile 和 fs.writefile 作为一项操作,然后将文件从 Web 服务器复制到我的计算机,但我认为我仍然无法执行这些相同的操作。无论如何,跳过中间的东西。如何使用 fs.readfile 和 writefile 创建两个单独的函数来复制文件?这是我一直在研究的内容,是的,我已经广泛阅读了这些论坛以寻找答案。
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.
我希望能够下载任何类型的文件,只需制作原始副本,将 md5 哈希等附加到 JSON 文件。不过,这可能是以后的问题。
回答by verybadalloc
As suggested by dandavis in his comment, readFiledoes nothing because it is an asynchronous call. Check out this answerfor additional information on what that means.
正如 dandavis 在他的评论中所建议的那样,readFile什么都不做,因为它是一个异步调用。查看此答案以获取有关这意味着什么的更多信息。
In short, an async call will never wait for the result to return. In your example, getDatadoes 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 readFileand writeFile.
简而言之,异步调用永远不会等待结果返回。在您的示例中,getData不会等待readFile()返回您想要的结果,而是会立即完成。异步调用通常通过传递来处理callbacks,这是传递给readFileand的最后一个参数writeFile。
In any case, there are two ways to do this:
无论如何,有两种方法可以做到这一点:
1.Do it asynchronously (which is the proper way):
1.异步执行(这是正确的方法):
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 readFileand writeFileby readFileSyncand writeFileSyncrespectively. 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).
2.同步进行。您的代码不会有太大的变化,你只需要更换readFile,并writeFile通过readFileSync和writeFileSync分别。警告:使用这种方法不仅违背了最佳实践,而且违背了使用 nodejs 的真正目的(当然,除非你有非常正当的理由)。
Edit: As per OP's request, here is one possible way to separate the two methods, e.g., using callbacks:
编辑:根据 OP 的要求,这是一种分离这两种方法的可能方法,例如,使用回调:
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.
这样,您将读取部分 (in getFileContent) 与复制部分分开。
回答by Trevor
I had to use this recently, so I converted verybadallocs answer to promises.
我最近不得不使用它,所以我将 verybadallocs 的答案转换为承诺。
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
})
回答by Lord
To read and write a file with Non-blocking or Asynchronous way, you can use the advance features of es6 or higher like Promise or Async/await, but you must keep eye on Polyfills(https://javascript.info/polyfills) or if there are only a couple of read/write you can use call back Hell.
以非阻塞或异步方式读写文件,你可以使用 es6 或更高版本的高级特性,如 Promise 或 Async/await,但你必须关注Polyfills( https://javascript.info/polyfills) 或如果只有几个读/写,你可以使用回调地狱。
function readFiles(){
fs.readFile('./txt/start.txt', 'utf-8', (err, data1)=>{
if(err) return console.log(err);
fs.readFile(`./txt/${data1}.txt`, 'utf-8', (err, data2)=>{
if(err) return console.log(err);
fs.readFile('./txt/append.txt', 'utf-8', (err, data3)=>{
if(err) return console.log(err);
writeFile('./txt/final.txt', `${data2}\n${data3}`);
});
});
});
}
function writeFile(path, data){
fs.writeFile(path,data,'utf-8',err=>{
if(err){
console.log(err);
}
})
}
readFiles();

