gpt4 book ai didi

javascript - 为什么我的 fs.readFileSync 不起作用

转载 作者:行者123 更新时间:2023-12-02 18:18:06 25 4
gpt4 key购买 nike

为什么这段代码不起作用?如果我评论 fs.readFileSync('file.html');代码有效并创建文件“file.html”但如果我取消注释, fs.writeFileSync 将不起作用,并且程序会崩溃并出现错误:

fs.js:427 return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode); ^ Error: ENOENT, no such file or directory 'file.html' at Object.fs.openSync (fs.js:427:18) at Object.fs.readFileSync (fs.js:284:15) at Object. (/home/pedro/startupEngineering/hw3/Bitstarter/testrestler.js:15:6) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:901:3

#!/usr/bin/env node


var fs = require('fs');
var rest = require('restler');

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');
}

else {
exports.checkHtmlFile = checkHtmlFile;
}

最佳答案

改变

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

第二个参数为rest.get(Url).on是一个异步回调函数,当 complete 时会调用该函数发生,然后才创建文件。但您正在阅读该文件,甚至在 complete 之前。发生。这就是您收到此错误的原因。

关于javascript - 为什么我的 fs.readFileSync 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19081270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com