Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我的fs.readFileSync不工作_Javascript_Node.js_Fs - Fatal编程技术网

Javascript 为什么我的fs.readFileSync不工作

Javascript 为什么我的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

为什么这个代码不起作用? 如果我评论 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:3


在触发
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/');
}