我正在创建一个文件夹(如果不存在)并在其中写入文件。但是下面的代码给了我
let fs = require('fs');
let mkdirp = require('mkdirp');
let path = require('path');
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
................
var dir = '/home/malintha/test';
mkdirp(dir, function(err) {
// path exists unless there was an error
});
fs.writeFile("/home/malintha/test/malintha.txt", data, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
}
.................
给我
{ Error: ENOENT: no such file or directory, open '/home/malintha/test/malintha.txt'
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/home/malintha/test/malintha.txt' }
此问题的原因是什么?
答案 0 :(得分:1)
mkdirp
是异步的;您可以use mkdirp.sync
,在回调中写入文件或使内容变质。该模块的GH页面上的示例也显示了这一点:
mkdirp('/tmp/foo/bar/baz', function (err) {
if (err) console.error(err)
else console.log('pow!') // <=- Your stuff goes here.
});
看到else
子句吗?这意味着它已创建。您很可能在创建之前就在写作。