学习节点和模块/使用创build文件

我真的是新的节点,觉得我什么都不懂。 我在看fs.writeFileSync创build一个新文件的教程。 然而,我的代码不工作,没有文件正在创build – 有人知道为什么吗? 另外为什么我需要

var fs=require("fs"); 

? 据我所知fs是模块中的一个构build,如果我们需要的东西,应该有另一个文件导出的东西(我们需要使用fs模块)? 节点是很难理解,并会感谢一些解释! 谢谢

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

FS确实是一个内置模块的节点,和其他模块一样,你必须要求它使用它的function。 你所指的文件是内部存在的,所以你不必npm安装它。

而关于你的代码,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')); 

另外,我认为你应该继续阅读节点的asynchronousfunction,以便更好地理解这种技术,以及它的优点。 这是你可以学习的一个网站,但有很多其他的好东西。