基于otherquestions(如下所示)和文档,我有以下代码,当它不存在时,应该创建一个新的目录和文件,或者当它存在时,应该替换它:
require('fs')
;(async ()=>{
//ref 1
fs.closeSync(fs.openSync('./newpath/newfile', 'w')); // make sure path and file exists
let mystream = fs.createWriteStream('./newpath/newfile',{encoding:'binary',flags : 'w'})
//ref2
await new Promise(r=> mystream.on('open'),(r)=>{r()})
let whyohwhy = Buffer.from("Should this be easy?")
mystream.write(whyohwhy,'binary',e=>console.log('Written to ./newpath/newfile'))
})();
参考1:https://stackoverflow.com/a/12809419/1461850
参考2:https://stackoverflow.com/a/12906805/1461850
其他“几乎”的问题:
File and folders create if not exist
Creating a file only if it doesn't exist in Node.js
Create a file if it doesn't already exist
唉,我得到这个错误
Promise {
<rejected> Error: ENOENT: no such file or directory, open './newpath/newfile'
at Object.openSync (fs.js:498:3)
at REPL10:3:17
at REPL10:9:3
at Script.runInThisContext (vm.js:133:18)
at REPLServer.defaultEval (repl.js:486:29)
at bound (domain.js:416:15)
at REPLServer.runBound [as eval] (domain.js:427:12)
at REPLServer.onLine (repl.js:819:10)
at REPLServer.emit (events.js:388:22)
at REPLServer.emit (domain.js:470:12) {
errno: -4058,
syscall: 'open',
code: 'ENOENT',
path: './newpath/newfile'
}
}
> (node:13988) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open './newpath/newfile'
at Object.openSync (fs.js:498:3)
at REPL10:3:17
at REPL10:9:3
at Script.runInThisContext (vm.js:133:18)
at REPLServer.defaultEval (repl.js:486:29)
at bound (domain.js:416:15)
at REPLServer.runBound [as eval] (domain.js:427:12)
at REPLServer.onLine (repl.js:819:10)
at REPLServer.emit (events.js:388:22)
at REPLServer.emit (domain.js:470:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13988) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13988) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
是否有一种简单/规范的方法来创建写入初始化writeStream(如果不存在,则创建路径/文件,如果存在,则替换路径/文件)?
2条答案
按热度按时间hxzsmxv21#
我刚想到这个,我做的就是扩展
Writable
,如下所示:}
数据将在流中进行内部缓冲,直到文件打开为止,而不会阻塞主线程。
mwkjh3gx2#
我设法用
fs-extra
module的ensureFile
function做到了这一点:不过,我对其他方法很感兴趣......