首先。從fs.existsSync()
man pages:
使用fs.exists()調用fs.open()之前檢查文件是否存在,fs.readFile()或不推薦fs.writeFile()。這樣做會引入爭用條件,因爲其他進程可能會更改兩個調用之間的文件狀態。相反,用戶代碼應直接打開/讀取/寫入文件,並處理文件不存在時引發的錯誤。
所以,如果你太重寫你的邏輯,同時建議考慮在內,並加入了一下path
模塊邏輯@Hogan建議的:
var fs = require("fs");
var path = require('path');
console.log(process.cwd()); // C:\Users\Usr1\Documents\Node\Test1
var file="C:\\Users\\Usr1\\Documents\\Node\\Test1\\input.txt";
fs.open(path.normalize(file), 'rx', function(err, fd){
if (err) console.log(err); // consoling the actual error may help in troubleshooting what the issue is...
// do something now...
});
我不是在UNIX – ElenaDBA
你可以向我們顯示你的'file'和'process.cwd()'的輸出? – sadmicrowave
請嘗試'/'和/或閱讀這個=> https://shapeshed.com/writing-cross-platform-node/ – Hogan