学习节点和模块/使用创建文件(learning node and modules / creating a file using)

编程入门 行业动态 更新时间:2024-10-28 03:23:22
学习节点和模块/使用创建文件(learning node and modules / creating a file using)

我真的对节点很新,觉得我什么都不懂。 我正在观看fs.writeFileSync创建新文件的教程。 但是我的代码不起作用并且没有创建文件 - 有人知道为什么吗? 我也为什么需要

var fs=require("fs");

? 据我所知,fs是一个内置模块,如果我们需要一些东西,应该有另一个文件导出一些东西(我们需要使用fs模块)? 节点有点难以理解,并会欣赏一些解释! 谢谢

var fs=require("fs"); fs.writeFileSync("contents.txt","Thats a new file") console.log(fs.writeFileSync("contents.txt").toString());

Im really new to node and feel like I understand nothing. I was watching a tutorial where the fs.writeFileSync creates a new file. However my code doesn't work and no file is being created-does someone know why? Also why do I need

var fs=require("fs");

? As I understand fs is a build in module and if we require something, there should be another file that exports something (which we require using the fs module)? Node is kind of hard to understand and would appreciate some explanation! Thanks

var fs=require("fs"); fs.writeFileSync("contents.txt","Thats a new file") console.log(fs.writeFileSync("contents.txt").toString());

最满意答案

fs确实是一个节点内置模块,而且作为其他模块,您必须要求它使用它的功能。 您所引用的文件在内部存在,因此您无需安装它。

关于你的代码,fs.writeFileSync应该像你使用它一样工作,但是,当你试图打印它时,你再次使用这个函数,这次没有内容,可能导致混淆。 应该完美运行的代码是:

//Requiring the fs module in order to use it later on var fs = require('fs'); //Writing "Thats a new file" as text to a new file called "contents.txt" in the same directory as the script file. fs.writeFileSync('contents.txt', 'Thats a new file'); //If you want to print the file, read it, like so. console.log(fs.readFileSync('contents.txt'));

另外,我认为你应该继续阅读有关节点异步功能的内容,这样你就可以更好地理解这项技术以及它有什么用处。 这是一个你可以学习的网站,但还有很多其他好的网站。

fs is indeed a node built-in module, and as other modules, you must require it to use its capabilities. the file you're referring is present internally, so you don't have to npm install it.

And regarding your code, fs.writeFileSync should work as you used it, however, when you tried to print it, you used this function again, this time with no contents, what probably caused the mix-up. Code that should work perfectly is:

//Requiring the fs module in order to use it later on var fs = require('fs'); //Writing "Thats a new file" as text to a new file called "contents.txt" in the same directory as the script file. fs.writeFileSync('contents.txt', 'Thats a new file'); //If you want to print the file, read it, like so. console.log(fs.readFileSync('contents.txt'));

Also, I think you should continue reading about node's async capabilities so you can understand better this technology and what is it good for. This is one site you can learn from but there are a lot of other good ones out there.

更多推荐

本文发布于:2023-07-31 01:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   模块   文件   learning   file

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!