我一直在尝试在使用Node.js时写入文件,但没有成功。我该怎么做?
当前回答
我喜欢的索引/文章/文件系统。
这对我有用。
另请参阅如何在node.js中写入文件?。
fs = require('fs');
fs.writeFile('helloworld.txt', 'Hello World!', function (err) {
if (err)
return console.log(err);
console.log('Wrote Hello World in file helloworld.txt, just check it');
});
helloworld.txt的内容:
Hello World!
更新:就像在当前目录中写入Linux节点一样,在其他一些目录中似乎没有,所以我添加了这条注释,以防万一:使用此ROOT_APP_PATH=fs.realpathSync('.');console.log(ROOT_APP_PATH);以获取文件的写入位置。
其他回答
文件系统API中有很多细节。最常见的方法是:
const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
// Or
fs.writeFileSync('/tmp/test-sync', 'Hey there!');
你当然可以让它更高级一点。非阻塞、写入位和段,而不是一次写入整个文件:
var fs = require('fs');
var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
stream.write("My first row\n");
stream.write("My second row\n");
stream.end();
});
同步写入
fs.writeFileSync(文件,数据[,选项])
fs = require('fs');
fs.writeFileSync("foo.txt", "bar");
异步写入
fs.writeFile(文件,数据[,选项],回调)
fs = require('fs');
fs.writeFile('foo.txt', 'bar', (err) => { if (err) throw err; });
哪里
file <string> | <Buffer> | <URL> | <integer> filename or file descriptor
data <string> | <Buffer> | <Uint8Array>
options <Object> | <string>
callback <Function>
值得阅读官方文件系统(fs)文档。
更新:async/await
fs = require('fs');
util = require('util');
writeFile = util.promisify(fs.writeFile);
fn = async () => { await writeFile('foo.txt', 'bar'); }
fn()
您可以使用库简易文件管理器
首先从npm安装npm安装简易文件管理器
上载和删除文件的示例
var filemanager = require('easy-file-manager')
var path = "/public"
var filename = "test.jpg"
var data; // buffered image
filemanager.upload(path,filename,data,function(err){
if (err) console.log(err);
});
filemanager.remove(path,"aa,filename,function(isSuccess){
if (err) console.log(err);
});
var fs = require('fs');
fs.writeFile(path + "\\message.txt", "Hello", function(err){
if (err) throw err;
console.log("success");
});
例如:读取文件并写入另一个文件:
var fs = require('fs');
var path = process.cwd();
fs.readFile(path+"\\from.txt",function(err,data)
{
if(err)
console.log(err)
else
{
fs.writeFile(path+"\\to.text",function(erro){
if(erro)
console.log("error : "+erro);
else
console.log("success");
});
}
});