我刚刚开始学习节点。这是我的问题,我得到了sample.js文件
var fs=require("fs");
console.log("starting");
fs.readFile("hello.txt" , function(error,data){
console.log("content is asdas " + data);
});
console.log("executed");
和带有内容的hello.txt,它们都在我的桌面上
hello
当我在Powershell或cmd中以管理员身份运行此文件时
C:\Windows\system32\ node C:\Users\X\Desktop\sample.js
我懂了
开始
执行中
内容为asdas未定义
当我记录错误
var fs=require("fs");
console.log("starting");
fs.readFile("hello.txt" , function(error,data){
console.log("content is asdas " + error);
});
console.log("executed");
我懂了
开始
执行中
内容为asdas错误:ENOENT,打开“ C:\ Windows \ system32 \ hello.txt”
所以我想这是该节点正在system32中而不是在桌面中查找错误??
谢谢!
Node.js从当前工作目录而不是从当前脚本/模块解析相对路径。
如果在使用所有
from
路径之后仍然找不到绝对路径,则也将使用当前工作目录。
在这种情况下,将是:
console.log(process.cwd());
// outputs: C:\Windows\system32\
要指定相对于脚本的路径,您必须解析/加入/ etc。您自己的路径__dirname
:
fs.readFile(__dirname + "/hello.txt", /* ... */);
fs.readFile(path.join(__dirname, "hello.txt"), /* ... */);
fs.readFile(path.resolve(__dirname, "hello.txt"), /* ... */);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句