Javascript 为什么我的fs.readFileSync不工作
为什么这个代码不起作用? 如果我评论 fs.readFileSync('file.html'); 代码运行正常,并创建文件“file.html” 但是如果我取消对其注释,fs.writeFileSync将无法工作,程序将崩溃并出现错误: 财政司司长:427 返回binding.open(pathModule.\u makeLong(path)、stringToFlags(flags)、mode); ^ 错误:enoint,没有这样的文件或目录“file.html” 在Object.fs.openSync(fs.js:427:18) 在Object.fs.readFileSync(fs.js:284:15) 反对。(/home/pedro/startupEngineering/hw3/Bitstarter/testrestler.js:15:6) 在模块处编译(Module.js:456:26) 在Object.Module.\u extensions..js(Module.js:474:10) 在Module.load(Module.js:356:32) 在Function.Module.\u加载(Module.js:312:12) 位于Function.Module.runMain(Module.js:497:10) 启动时(node.js:119:16) 在node.js:901:3Javascript 为什么我的fs.readFileSync不工作,javascript,node.js,fs,Javascript,Node.js,Fs,为什么这个代码不起作用? 如果我评论 fs.readFileSync('file.html'); 代码运行正常,并创建文件“file.html” 但是如果我取消对其注释,fs.writeFileSync将无法工作,程序将崩溃并出现错误: 财政司司长:427 返回binding.open(pathModule.\u makeLong(path)、stringToFlags(flags)、mode); ^ 错误:enoint,没有这样的文件或目录“file.html” 在Object.fs.open
在触发
complete
事件之前,您不会写入文件,但会立即尝试从中读取
因为它还不存在,所以您会得到一个异常,您无法捕获它,因此程序会在complete
事件触发并写入文件之前退出
您需要将尝试从文件读取的代码移动到写入文件的事件处理程序中。更改
var restlerHtmlFile = function(Url) {
rest.get(Url).on('complete', function(result) {
fs.writeFileSync('file.html',result);
});
};
if(require.main == module) {
restlerHtmlFile('http://obscure-refuge-7370.herokuapp.com/');
fs.readFileSync('file.html');
}
到
rest.get(Url.on
的第二个参数是一个异步回调函数,它将在发生complete
时调用,只有在创建文件时才会调用。但是您正在读取文件,甚至在完成之前。这就是您出现此错误的原因。没有此类文件或目录“file.html”
var restlerHtmlFile = function(Url) {
rest.get(Url).on('complete', function(result) {
fs.writeFileSync('file.html',result);
});
};
if(require.main == module) {
restlerHtmlFile('http://obscure-refuge-7370.herokuapp.com/');
fs.readFileSync('file.html');
}
var restlerHtmlFile = function(Url) {
rest.get(Url).on('complete', function(result) {
fs.writeFileSync('file.html',result);
fs.readFileSync('file.html');
});
};
if(require.main == module) {
restlerHtmlFile('http://obscure-refuge-7370.herokuapp.com/');
}